How can I add “X-Content-Type-Options: nosniff” in

2019-08-17 10:10发布

问题:

I have modified the web.config as to prevent the mime sniff.

<configuration>
   <system.webServer>
      <httpProtocol>
         <customHeaders>
            <add name="X-Content-Type-Options" value="nosniff" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
</configuration>

but code scan tool still told me that global.asax.cs has the vulnerabilities

Application_BeginRequest is either empty or does not include a function call to set the X-Content-Type-Options to nosniff or attempts to remove that header.

So how to set X-Content-Type-Options: nosniff in Global.asax.cs ?

回答1:

Using in Web.Config

To add these headers, go to the <customHeaders> node previously added and add those headers inside the <customHeaders> node.

<httpprotocol> 
 <customheaders> 
    <add name="X-Content-Type-Options" value="nosniff "/>
 </customheaders> 
</httpprotocol>

Using global.asax.cs

protected void Application_PreSendRequestHeaders(Object source, EventArgs e) {
   HttpContext.Current.Request.Headers.Add("X-Content-Type-Options", "nosniff");
}