Set web.config transform in Asp.NET Core

user1820686 picture user1820686 · Mar 29, 2017 · Viewed 20.3k times · Source

I've just came across with problem of web.config transformation in asp.net core.

There are two files: base web.config and web.prod-zone-a.config. My aim is to use transformation inside web.prod-zone-a.config when publishing my project. I have the following "prod-zone-a" configuration settings in .csproj:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'prod-zone-a|AnyCPU' ">
    <IntermediateOutputPath>obj\Debug\netcoreapp1.1</IntermediateOutputPath>
    <DebugSymbols>true</DebugSymbols>
    <Optimize>false</Optimize>
    <DefineConstants>TRACE;DEBUG;NETCOREAPP1_1</DefineConstants>
    <Configuration>prod-zone-a</Configuration>
</PropertyGroup>

web.prod-zone-a.config looks like:

<system.webServer>
    <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore>
        <environmentVariables xdt:Transform="Replace">
            <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="prod-zone-a" />
        </environmentVariables>
    </aspNetCore>
</system.webServer>

I tried to run publish by two commands:

dotnet msbuild /t:Publish /p:OutputPath=c:\delivery /p:Configuration=prod-zone-a

and

dotnet publish --configuration prod-zone-a --output c:\delivery

But no transformation applies to web.config on output - just the default value. Do I miss something in configuration or command executing?

Answer

Sha picture Sha · Feb 15, 2019

This worked for me:

  1. Add web.release.config file to the project root.
  2. In Visual Studio 2017, Publish using Web Deploy (make sure it is set to Release). Settings will automatically be picked up.

Sample transformation:

    <?xml version="1.0"?>
    <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
        <system.webServer>
          <aspNetCore>
            <environmentVariables>
              <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="PRODUCTION" xdt:Locator="Match(name)" xdt:Transform="SetAttributes" />
            </environmentVariables>
          </aspNetCore>
        </system.webServer>
    </configuration>

Update: If you want to remove web.config.release file and others on publish, simply edit your .csproj file and add something like this:

  <ItemGroup>
    <Content Remove="appsettings.Development.json" />
    <Content Remove="web.release.config" />
  </ItemGroup>
  <ItemGroup>
    <None Include="appsettings.Development.json" />
    <None Include="web.release.config" />
  </ItemGroup>