Search code examples
asp.netasp.net-mvcweb-configtransform

Insert an element in web.config based on key value in appsettings


We have a requirement to apply a transform based upon an app setting value in web.config for our ASP.NET MVC project.

<!--web.config-->
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="environment:define" value="dev"/>
  </appSettings>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="https://abcd.com" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

I want the transform to insert a new element within the <customHeaders> element when the app-setting value env:define is acc.

Can anyone please suggest how this can be achieved?

Thank you in advance!


Solution

  • You can create a new solution configuration (e.g. acc) and add a web.acc.config transform file that manages both values:

    <appSettings>
      <add key="environment:define" value="acc" xdt:Locator="Match(key)" xdt:Transform="SetAttributes"/>    
    </appSettings>
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="https://abcd.com" xdt:Transform="Insert" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>
    

    Then choose this solution configuration whenever you want to use these values.