In a previous post I mentioned that we started to put environment variables inside our web.config files to change the ASPNETCORE_ENVIRONMENT setting inside our ASP.NET Core apps. As we were already using Web Deploy to deploy our ASP.NET Core applications, we decided to use the web.config transformations functionality to set the environment variable in our web.config to a correct value before deploying:
- We created extra web.{environment}.config files
- And added the Xdt transformation configuration:
However when we tried to deploy, we noticed that the transformation was not executed and that the original web.config file was used.
What did we do wrong?
The answer turned out to be “Nothing”. Unfortunately ASP.NET Core projects don’t support the transformation functionality. Luckily, a colleague(thanks Sami!) brought the following library under my attention: https://github.com/nil4/dotnet-transform-xdt
dotnet-transform-xdt
is a dotnet CLI tool for applying XML Document Transformation (typically, to ASP.NET configuration files at publish time, but not limited to this scenario).
That’s exactly what we need!
How to use dotnet-transform-xdt?
- Right click on your ASP.NET Core project and choose Edit csproj
- Add the following line to the list of Package references:
<DotNetCliToolReference Include="Microsoft.DotNet.Xdt.Tools" Version="2.0.0" />
- Add the following target before the closing </project>:
<Target Name="ApplyXdtConfigTransform" BeforeTargets="_TransformWebConfig">
<PropertyGroup>
<_SourceWebConfig>$(MSBuildThisFileDirectory)Web.config</_SourceWebConfig>
<_XdtTransform>$(MSBuildThisFileDirectory)Web.$(Configuration).config</_XdtTransform>
<_TargetWebConfig>$(PublishDir)Web.config</_TargetWebConfig>
</PropertyGroup>
< Exec Command="dotnet transform-xdt --xml "$(_SourceWebConfig)" --transform "$(_XdtTransform)" --output "$(_TargetWebConfig)"" Condition="Exists('$(_XdtTransform)')" />
< /Target>
- If you now run
dotnet publish
and examine theWeb.config
in the publish output folder, a transformed web.config should be there…