如何在 Global.asax.cs 中添加“X-Content-Type-Options: nosniff”以防止 mime 嗅探

all*_*arp 0 c# asp.net security asp.net-mvc

我修改了 web.config 以防止 mime 嗅探。

<configuration>
   <system.webServer>
      <httpProtocol>
         <customHeaders>
            <add name="X-Content-Type-Options" value="nosniff" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

但是代码扫描工具仍然告诉我 global.asax.cs 有漏洞

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.
Run Code Online (Sandbox Code Playgroud)

那么如何在 Global.asax.cs 中设置 X-Content-Type-Options: nosniff 呢?

VIG*_*LAM 6

在 Web.Config 中使用

要添加这些标头,请转到<customHeaders>先前添加的节点并将这些标头添加到<customHeaders>节点内。

<httpprotocol> 
 <customheaders> 
    <add name="X-Content-Type-Options" value="nosniff "/>
 </customheaders> 
</httpprotocol>
Run Code Online (Sandbox Code Playgroud)

使用 global.asax.cs

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