Complete Guide to Automating ASP.NET Web Application Publishing with MSBuild

Nov 23, 2025 · Programming · 14 views · 7.8

Keywords: MSBuild | ASP.NET | Web Deployment | TeamCity | Automated Build

Abstract: This article provides a comprehensive exploration of using MSBuild for automated publishing of ASP.NET web applications on TeamCity build servers. Based on practical project experience, it offers complete solutions ranging from basic configuration to advanced deployment scenarios, covering key aspects such as Web.config transformations, file packaging, and remote deployment. Through step-by-step examples and in-depth analysis, readers will learn enterprise-level web deployment best practices.

Introduction

In modern software development workflows, automated deployment is a critical component of continuous integration and continuous delivery. While Visual Studio provides convenient publishing features for ASP.NET web applications, in build server environments we need to achieve the same functionality through command-line tools. MSBuild, as the standard build tool in the .NET ecosystem, provides robust support for this purpose.

Fundamental Concepts and Principles

MSBuild, short for Microsoft Build Engine, serves as the standard build system for the .NET platform. In web application deployment scenarios, MSBuild utilizes predefined targets and tasks to automate compilation, transformation, and deployment processes.

The core requirements for web deployment include: compiling project code, applying Web.config transformations, filtering out runtime-unnecessary files, packaging deployment bundles, and copying output to target locations. These functions are implemented through graphical interfaces in Visual Studio, but must be accomplished using MSBuild commands and scripts on build servers.

TeamCity Environment Configuration

When configuring MSBuild deployment on TeamCity build servers, the following key parameters must be properly set:

Artifact paths: %system.teamcity.build.workingDir%\MyProject\obj\Debug\Package\PackageTmp
Type of runner: MSBuild (Runner for MSBuild files)
Build file path: MyProject\MyProject.csproj
Working directory: same as checkout directory
MSBuild version: Microsoft .NET Framework 4.0
MSBuild ToolsVersion: 4.0
Run platform: x86
Targets: Package
Command line parameters to MSBuild.exe: /p:Configuration=Debug

This configuration automatically completes compilation and packaging processes, including Web.config transformations. The packaged files are saved in the specified artifacts path, facilitating subsequent processing or direct deployment.

Detailed MSBuild Deployment Script

To address more complex deployment requirements, we can create specialized MSBuild script files. The following demonstrates a complete deployment script example:

<?xml version="1.0" encoding="utf-8" ?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
        <SolutionName>MySolution</SolutionName>
        <SolutionFile>$(SolutionName).sln</SolutionFile>
        <ProjectName>MyProject</ProjectName>
        <ProjectFile>$(ProjectName)\$(ProjectName).csproj</ProjectFile>
    </PropertyGroup>

    <Target Name="Build" DependsOnTargets="BuildPackage;CopyOutput" />

    <Target Name="BuildPackage">
        <MSBuild Projects="$(SolutionFile)" ContinueOnError="false" Targets="Rebuild" Properties="Configuration=$(Configuration)" />
        <MSBuild Projects="$(ProjectFile)" ContinueOnError="false" Targets="Package" Properties="Configuration=$(Configuration)" />
    </Target>

    <Target Name="CopyOutput">
        <ItemGroup>
            <PackagedFiles Include="$(ProjectName)\obj\$(Configuration)\Package\PackageTmp\**\*.*"/>
        </ItemGroup>
        <Copy SourceFiles="@(PackagedFiles)" DestinationFiles="@(PackagedFiles->'\\build02\wwwroot\$(ProjectName)\$(Configuration)\%(RecursiveDir)%(Filename)%(Extension)')"/>
    </Target>
</Project>

This script defines three main targets: Build (primary target), BuildPackage (build and package), and CopyOutput (copy output). The BuildPackage target first rebuilds the entire solution, then executes the Package target on the specific project to generate deployment packages. The CopyOutput target uses the Copy task to transfer packaged files to the specified network location.

Advanced Deployment with Web Deploy

For scenarios requiring remote deployment, Web Deploy (MSDeploy) offers more powerful capabilities. The following script demonstrates remote publishing using Web Deploy:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
    <ProjectFile Condition=" '$(ProjectFile)' == '' ">$(ProjectName)\$(ProjectName).csproj</ProjectFile>
    <DeployServiceUrl Condition=" '$(DeployServiceUrl)' == '' ">http://staging-server/MSDeployAgentService</DeployServiceUrl>
  </PropertyGroup>

  <Target Name="VerifyProperties">
    <!-- Verify that we have values for all required properties -->
    <Error Condition=" '$(ProjectName)' == '' " Text="ProjectName is required." />
  </Target>

  <Target Name="Build" DependsOnTargets="VerifyProperties">
    <!-- Deploy using windows authentication -->
    <MSBuild Projects="$(ProjectFile)"
             Properties="Configuration=$(Configuration);
                             MvcBuildViews=False;
                             DeployOnBuild=true;
                             DeployTarget=MSDeployPublish;
                             CreatePackageOnPublish=True;
                             AllowUntrustedCertificate=True;
                             MSDeployPublishMethod=RemoteAgent;
                             MsDeployServiceUrl=$(DeployServiceUrl);
                             SkipExtraFilesOnServer=True;
                             UserName=;
                             Password=;"
             ContinueOnError="false" />
  </Target>
</Project>

This script implements remote deployment through the MSDeployPublish target, supporting Windows authentication and automatically handling certificate validation and file synchronization. In TeamCity, configuration parameters can be passed through environment variables, enabling flexible deployment configurations.

Parameterization and Command Line Usage

To enhance script flexibility, we can make key parameters configurable. Configuration information can be passed through command-line parameters:

msbuild build.xml /p:Configuration=Staging;ProjectName=MyProject;DeployServiceUrl=http://staging-server/MSDeployAgentService

This approach allows the same deployment script to be used for different environments and projects, significantly improving code reusability.

Comparison with Alternative Deployment Methods

Beyond the methods described above, several other deployment approaches warrant consideration. The deployment profile (PublishProfile) method:

msbuild MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=<profile-name> /p:Password=<insert-password> /p:VisualStudioVersion=11.0

This approach is suitable for Visual Studio 2012 and later versions, simplifying deployment through predefined publishing profiles. Another method utilizes the _WPPCopyWebApplication target:

msbuild /t:ResolveReferences;_WPPCopyWebApplication /p:BuildingProject=true;OutDir=C:\Temp\build\ Test.csproj

This method directly invokes internal targets of the Web Publishing Pipeline, allowing more granular control over the deployment process.

Best Practices and Considerations

In practical projects, we recommend following these best practices: ensure correct versions of .NET Framework and Web Deploy tools are installed on build servers; conduct thorough testing before deployment, particularly validating Web.config transformations; use version control to manage deployment scripts for traceability; implement appropriate error handling and logging mechanisms.

For large projects, consider decomposing the deployment process into multiple phases: compilation, testing, packaging, deployment, with each phase having clear inputs, outputs, and verification steps. This approach enhances deployment reliability and maintainability.

Conclusion

Implementing automated publishing of ASP.NET web applications through MSBuild provides a powerful and flexible solution. Whether for simple file system deployments or complex remote server deployments, MSBuild offers appropriate tools and methods. Mastering these technologies enables teams to establish efficient, reliable continuous delivery pipelines, improving overall software development and deployment efficiency.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.