Search code examples
c#.netasp.net-mvcvisual-studioweb-config-transform

Visual Studio always reads configuration from base Web.config file even when different active configuration is selected during debugging


I have an ASP.NET MVC project targeting .NET 4.8. This project has 2 debug configurations namely debug and test-debug. I have created debug transform (web.test-Debug.config) for test-debug and I am also able to see preview of test-debug configuration and all my transforms are working as expected.

When I select test-debug as active debug configuration in Visual Studio and try to debug this project, Visual Studio reads configuration from web.config file and this file has debug configuration.

How can I force Visual Studio to read configuration for active build configuration which is test-debug? I tried this in both Visual Studio 2019 and 2022 without luck. Really appreciate any help.

Following is the way my config would look in visual studio

Web.config
-Web.test-debug.config


Solution

  • Visual studio performs transform only during the publish operation for web projects and not during the build.

    This makes sense because if visual studio transform the web.config file as per selected build configuration, developer might unintentionally end up checking in transformed web.config as the base configuration.

    This article describes the best fix available. Following are the details from the article.

    1. Unload the project

    2. Edit .csproj

    3. Append following to the end of the file just before

    4. Save .csproj and reload

    5. Open configuration manager

    6. Add a new Configuration Name: Base. Copy settings from: Release

    7. Copy the contents of your web.config

    8. Right click Web.Config > Add Config Transformation

    9. Overwrite the web.base.config with the contents of your clipboard

    From now on Web.Config will be overwritten using transformations.

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