Search code examples
c#asp.net-mvchttphttpsweb-config

Add header in web.config conditionally


Is there any way to make exceptions from a custom headers rule in web.config?

I have the header X-Frame-Options in web.config, which adds it for all files.

<httpProtocol>
  <customHeaders>
    <add name="X-Frame-Options" value="SAMEORIGIN" />
  </customHeaders>
</httpProtocol>

I want to exclude a few pages from this rule in the controller.

I cannot remove the header in the controller since web.config adds it after the controller is executed.

I also don't want to remove the header from web.config and then instead add it in the controller or in an attribute for the controller for all pages, because that would only add it for HTML files returned by a controller, not static HTML files, js files, pictures and more.

I don't know of a way to make the adding of the header in web.config conditional, if there is perhaps I could add a temporary header in the controller, and then write something like

<httpProtocol>
  <customHeaders>
    if(!header("allowembedding")){
      <add name="X-Frame-Options" value="SAMEORIGIN" />
    }
    <remove name="allowembedding" />
  </customHeaders>
</httpProtocol>

Solution

  • I believe you can make this work with the <location> element:

    <configuration>
      <!-- ... -->
    
      <location path="Path/To/Exclude">
        <system.webServer>
          <httpProtocol>
            <customHeaders>
              <remove name="X-Frame-Options" />
            </customHeaders>
          </httpProtocol>
        </system.webServer>
      </location>
    </configuration>