Wednesday, November 1, 2017

Web.config transformations in .NET Core

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

image

  • 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 &quot;$(_SourceWebConfig)&quot; --transform &quot;$(_XdtTransform)&quot; --output &quot;$(_TargetWebConfig)&quot;" Condition="Exists('$(_XdtTransform)')" />
< /Target>

  • If you now run dotnet publish  and examine the Web.config in the publish output folder, a transformed web.config should be there…

2 comments:

Sumathi said...

I appreciate your style of writing because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also informative. I hope to read more and more interesting articles from your blog. All the best.
Psoriasis Shampoo

Sita said...

Interesting blog post. This blog shows that you have a great future as a content writer. waiting for more updates.
Herbal Shampoo
Dandruff Treatment
Antifungal Cream
Vitiligo Medicines