web.config 设置 X-Frame-Options 的方法

本文解决了一个常见的网站安全问题,即X-Content-Type-Options Header缺失导致的资源加载错误。通过正确设置JS文件的内容类型为application/javascript;charset=utf-8,可以避免浏览器因MIME类型不匹配而阻止执行JS文件的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网站检测提示 X-Content-Type-Options Header Missing,在网上找资料发现都是其他的设置方法,没有在这里插入图片描述
在网上找解决办法,都是说添加X-CONTENT-TYPE-OPTIONS to NOSNIFF,而网上资料都是php的解决方法,C#的解决方法很少。
在web.config 配置文件中添加如下响应头

<system.webServer>
  <httpProtocol> 
    <customHeaders>
      <add name="X-Content-Type-Options" value="nosniff"/>
      <add name="X-XSS-Protection" value="1;mode=block"/>
      <add name="X-Frame-Options" value="SAMEORIGIN"/>
           <add name="Content-Security-Policy" value="default-src 'self' i.tianqi.com"/>

    </customHeaders>
  </httpProtocol>
</system.webServer>

We started facing this error in production after our devops team changed the webserver configuration by adding X-Content-Type-Options: nosniff. Now, due to this, browser was forced to interpret the resources as it was mentioned in content-type parameter of response headers.

Now, from the beginning, our application server was explicitly setting content-type of the js files as text/plain. Since, X-Content-Type-Options: nosniff was not set in webserver, browser was automatically interpreting the js files as JavaScript files although the content-type was mentioned as text/plain. This is called as MIME-sniffing. Now, after setting X-Content-Type-Options: nosniff, browser was forced to not do the MIME-sniffing and take the content-type as mentioned in response headers. Due to this, it did interpret js files as plain text files and denied to execute them or blocked them. The same is shown in your errors.

Solution: is to make your server set the content-type of JS files as

application/javascript;charset=utf-8
This way, it will load all JS files normally and issue will get resolved.
在《Hardening your HTTP response headers》文章中,作者讲的更清楚。
参考:https://zp.xz-hc.com/news/show-5207.html
https://stackoverflow.com/questions/40728554/resource-blocked-due-to-mime-type-mismatch-x-content-type-options-nosniff
Hardening your HTTP response headers,https://scotthelme.co.uk/hardening-your-http-response-headers/#x-content-type-options
https://www.ilovefreesoftware.com/09/featured/check-if-x-xss-protection-is-enabled-in-http-header-on-your-website.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值