Search code examples
.netasp.net-mvcweb-configwebmatrixweb.config-transform

Web.config transforms add tree


I want to add the following to the web config on release:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" xdt:Transform="Insert" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

There aren't any custom headers in the default web config so I get an error when I publish: No element in the source document matches '/configuration/system.webServer/httpProtocol/customHeaders'.

I can fix it my just adding the empty elements to the web.config like so:

  <httpProtocol>
    <customHeaders>
    </customHeaders>
  </httpProtocol>

However, it doesn't feel like the correct way.

Is there a more correct way to build the element tree on the transform?


Solution

  • Adding the empty <customHeaders> node to the web.config works because the transform you have is to insert the <add .../> node, not the <customHeaders> node. It can only insert where it matches to that point.

    To insert the tree of nodes, move the xdt:Transform="Insert" up a little in the XML. If you start with a web.config of:

    <?xml version="1.0">
    <configuration>
      <system.webServer>
        <httpProtocol />
      </system.webServer>
    </configuration>
    

    and transform it with:

    <?xml version="1.0">
    <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
      <system.webServer>
        <httpProtocol>
          <customHeaders xdt:Transform="Insert">
            <add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" />
          </customHeaders>
        </httpProtocol>
      </system.webServer>
    </configuration>
    

    You'll end up with:

    <?xml version="1.0">
    <configuration>
      <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" />
          </customHeaders>
        </httpProtocol>
      </system.webServer>
    </configuration>
    

    Here's a helpful web.config transformation tester.