Search code examples
c#asp.netweb-configvisual-studio-2019web-config-transform

ASP.NET: xdt:Transform does not insert new section in web.config file


I am working with ASP.NET 4.7.2. I have the following web.config file:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="foo" connectionString="value"/>
  </connectionStrings>
  <system.web>
    <customErrors mode="Off"/>
  </system.web>
</configuration>

and the following web.debug.config file:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <xdt:Import assembly="AppHarbor.TransformTester" namespace="AppHarbor.TransformTester.Transforms"/>

  <configSections xdt:Transform="MergeBefore(/configuration/*)" />

  <appSettings>
    <add key="key1" value="1" xdt:Transform="Insert"/>
  </appSettings>

</configuration>

When I do preview changes on Visual Studio 2019, I don't see key1 being added, and if I run the above in WebConfigTransformationTester, I get the following error:

<error>No element in the source document matches '/configuration/appSettings/add'</error>

What am I doing wrong? How can I make sure that my new section is added?


Solution

  • I seem to have found the problem. The xdt:Transform="Insert" command needs to be specified when the <appSettings> section is defined, and not inside it:

      <appSettings xdt:Transform="Insert">
        <add key="key1" value="1"/>
      </appSettings>
    

    My transform is now correct:

    <?xml version="1.0"?>
    <configuration>
      <connectionStrings>
        <add name="foo" connectionString="value" />
      </connectionStrings>
      <system.web>
        <customErrors mode="Off" />
      </system.web>
      <appSettings>
        <add key="key1" value="1" />
      </appSettings>
    </configuration>