Web.Config Transforms in .Net Core

Within .Net Core we can set the ASPNETCORE_ENVIRONMENT inside our web.config files.

The ASPNETCORE_ENVIRONMENT can have any value but by convention we tend to use:

  • Development
  • Stating
  • Productiuon

By changing the ASPNETCORE_ENVIRONMENT we can run different code in differen environments. For example you may want to bundle and minify your JS files in prodcution, but use the original files within the development environment:

@* JS files that are used in the layout files *@
<environment include="Development">
    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/lib/jquery-ui/jquery-ui.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
    <script src="~/lib/knockout/knockout.js"></script>
<environment exclude="Development">
    <script src="~/js/bundle.min.js" asp-append-version="true" ></script>

To set the ASPNETCORE_ENVIRONMENT for different environments you can create additional web.config environment files, and use the web.config transformation functionality to transform the web.config file for each environment.

e.g. web.config:

<?xml version="1.0" encoding="utf-8"?>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\">
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />

    <!-- Removed for brevity -->

e.g. web.release.config

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>

Unfortunately, when we publish the site .Net Core does not support the transformations, and we have to add an additional NuGet package in to do it:

  • Add the following reference in your project file:
    <DotNetCliToolReference Include="Microsoft.DotNet.Xdt.Tools" Version="2.0.0" />

Note - when I tried to add this via the ‘Manage NuGet packages…’ I got the following error:

Package ‘Microsoft.DotNet.Xdt.Tools 2.0.0’ has a package type ‘DotnetCliTool’ that is not supported by project…

The following link suggests adding the reference directly into the project file like we did as a work around:

Finally you will need to add the following just before the closing tag:

<Target Name="ApplyXdtConfigTransform" BeforeTargets="_TransformWebConfig">
   <Exec Command="dotnet transform-xdt --xml &quot;$(_SourceWebConfig)&quot; --transform &quot;$(_XdtTransform)&quot; --output &quot;$(_TargetWebConfig)&quot;" Condition="Exists('$(_XdtTransform)')" />
< /Target>

Now when you publish your site, the ASPNETCORE_ENVIRONMENT should be correctly transformed in the web.config file.

Alex Orpwood Written by:

Software developing and architecting for 20 years. Satellite monitoring by day, writing my own app by night. More about me