Modifiying a Connection String in a Web Deploy


Click here to change the theme.

When developing a web site that uses a database and that is to be deployed using Web Deploy it is usually necessary to modify the connection string to be used in the other environment. Assuming you only need to change the connection string for just a specific Web Deploy then you can do that with a transformation. The following should show exactly what you need to do to do that. In my opinion the Microsoft documentation is too general and tries to satisfy too many possibilities.

In Solution Explorer expand the Properties node to get the PublishProperties as in the following.

Right-click on the Web Deploy profile and select Add Config Transform as shown in the following.

You will get a Web.project - Web Deploy.config file in the Web Config node. The initial contents will be the following.

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
    In the example below, the "SetAttributes" transform will change the value of 
    "connectionString" to use "ReleaseSQLServer" only when the "Match" locator 
    finds an attribute "name" that has a value of "MyDB".
    
    <connectionStrings>
    <add name="MyDB" 
        connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" 
        xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
    </connectionStrings>
-->
<system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
    <!--
    In the example below, the "Replace" transform will replace the entire 
    <customErrors> section of your web.config file.
    Note that because there is only one customErrors section under the 
    <system.web> node, there is no need to use the "xdt:Locator" attribute.
      
    <customErrors defaultRedirect="GenericError.htm"
        mode="RemoteOnly" xdt:Transform="Replace">
        <error statusCode="500" redirect="InternalError.htm"/>
    </customErrors>
    -->
</system.web>
</configuration>

Change the sample to the following or add the following.

<connectionStrings>
  <add name="csname"
    connectionString="yourconnectionstring"
    xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>

Where csname is the name in the Web.config of your connection string that you need to replace in the deployment. Do not change name in "Match(name)".

That transformation is saying that you want to search for the connection string that has the specified name and then change the connection string value during the deployment.

There are many other transformations possible but if you only need to change the connection string for a specific Web Deploy then that should be the most straight forward.