简体   繁体   中英

Understanding ASP.NET Web.config transformations - Web.Debug.config

I've been strugling with this for one hour and can't find to simple explanation or at least some Microsoft documentation that states this.

I want to understand behaviour of next files:

  • Web.config
  • Web.Debug.config
  • Web.Release.config
  • Web.Staging.config (I created this using Right click on Web.config -> Add Config Transform)

I added next appSetting in Web.config file:

<configuration>
  ..
  <appSettings>
    <add key="DevDisplayPanel" value="default value" />
  </appSettings>
  ..
</configuration>

In my Web.Debug.config I changed DevDisplayPanel to this:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings>
    <add key="DevDisplayPanel" 
         xdt:Transform="Replace" 
         xdt:Locator="Match(key)" 
         value="Debug mode" />
  </appSettings>
</configuration>

I displayed the appSettings item like this:

ViewBag.Test = System.Configuration.ConfigurationManager.AppSettings["DevDisplayPanel"];

I understood that if I run Debug -> Start Debugging in Visual Studio that DevDisplayPanel setting will be read from Web.Debug.config . I can't find a Microsoft documentation stating this.

I tried to run my web application using Debug, Release and Staging solution configuration but they all show DevDisplayPanel value from file Web.config .

Where do files Web.Debug|Release|MyConfiguraton.config come into play. What have I missed and most importantly again this behaviour should be noted in bold somewhere in the docs!!

Web.config transformations are associated with Publishing your project in a given configuration.

When you debug in Visual Studio, it always uses the plain web.config file, no matter what the Configuration.

You need to choose Build => Publish from the menu options and then run the published application.

Credit to https://gist.github.com/EdCharbeneau/9135216

You can add something like this to the bottom of your .csproj

 <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets" />
  <Target Name="BeforeBuild">
    <TransformXml Source="Web.config" Transform="Web.$(Configuration).config" Destination="Web.config" />
  </Target>

v16 is visual studio 2019.

Note, that this will overwrite your original web.config with any changes from the transforms. I'm actually talking it over with my team how best to do this in our project, and one solution is to put all your "standard" settings that you debug your project with, but in the web.debug.config. And treat that like your "base" web.config.

Using this snippet has the added benefit of working on your build server prior to a deploy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM