Search code examples
c#visual-studioasp.net-corehttpswebdeploy

How to exclude auto generated web.config file when doing web deploy ASP.NET Core API (.NET 5)


I have ASP.NET Core (.NET 5) API and want to deploy use web deploy visual studio.
Also on the windows server, I configured HTTPS in web.config file. So after publishing a new version of API, web.config file updating and I'm losing my configuration.

Can you please recommend a solution for avoiding this situation?


Solution

  • You can use web.config custom transformation as described here

    Custom transformations are run last, after Build configuration, Profile, and Environment transforms.

    Include a {CUSTOM_NAME}.transform file for each custom configuration requiring a web.config transformation.

    In the following example, a custom transform environment variable is set in custom.transform:

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

    The transform is applied when the CustomTransformFileName property is passed to the dotnet publish command:

    dotnet publish --configuration Release /p:CustomTransformFileName=custom.transform
    

    The MSBuild property for the profile name is $(CustomTransformFileName).

    Similar question has been posted before: Can I override a connection string in the web.config for local development?

    I think the best suggested solution is the following:

    Web.config

    <configuration>
      <connectionStrings configSource="connectionstrings.config">
      </connectionStrings>
    </configuration>
    

    connectionstrings.config (not in source control)

    <connectionStrings>
      <add name="cs" connectionString="server=.;database=whatever;"/>
    </connectionStrings>
    

    Each developer can choose which database their local machine points to, and as long as the connectionstrings.config file is not in source control (add it to the ignore list), nobody will step on each other's feet.