【问题标题】:.NET Add header to response on index.html request?.NET 将标头添加到 index.html 请求的响应中?
【发布时间】:2020-03-26 09:34:12
【问题描述】:

我有一个名为 Mensajes.Cliente 的 WebAPI 项目,其中包含一个 Angular 应用程序:

出于安全原因,我需要为每个服务器响应添加 2 个标头。解决了将以下内容添加到 Global.asax:

protected void Application_BeginRequest()
{
    Response.AddHeader("X-Frame-Options", "DENY");
    Response.AddHeader("X-XSS-Protection", "1");
}

当我调用任何控制器方法时,响应确实包含两个标头,因此可以正常工作。

但是当我尝试将 index.html 设置为 foo.com/Mensajes.Clientefoo.com/Mensajes.Cliente/index.html 时,没有设置标头(所有静态内容都是 .js 或 .css 文件时会发生这种情况)。

如何将这些标头添加到每个服务器请求的响应中?

这些标头必须在 web.config 或 Global.asax 配置中设置,还是在服务器配置中设置?

【问题讨论】:

    标签: .net asp.net-web-api http-headers asp.net-web-api2


    【解决方案1】:
    1. 为网站的所有内容设置标题的最简单方法是在web.configsystem.webServerhttpProtocol 下的customHeaders 部分将确保所有文件和响应都包含此标头。

    例子:

    <system.webServer>
       <!--.......-->
        <httpProtocol>
          <customHeaders>
            <add name="X-Frame-Options" value="DENY" />
            <add name="X-XSS-Protection" value="1" />
          </customHeaders>
        </httpProtocol>    
        <!--.......-->
    </system.webServer>
    
    1. 另一个选项是创建自定义HttpModule。这样,您可以更好地控制需要附加标头的文件和内容。

    例子:

    public class CustomOrgHeaderModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }
    
        public void Dispose() { }
    
        void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            //To add header only for Html files
           //You can add any condition as you need
            if (HttpContext.Current.Request.Url.ToString().Contains(".html"))//css, js as you need
            {
                HttpContext.Current.Response.Headers.Add("X-Frame-Options", "DENY");
                HttpContext.Current.Response.Headers.Add("X-XSS-Protection", "1");
            }
        }
    }
    

    并在web.config 中注册CustomOrgHeaderModule -

       <system.webServer>
           <!--.......-->
            <modules>
             <add name="CustomHeaderModule" type="SOFTEST.NET.API.Modules.CustomOrgHeaderModule" /><!--.SOFTEST.NET.API.Modules.CustomOrgHeaderModule is then FullNmae of the class MEANS Namesapce.CassName -->
           </modules>  
            <!--.......-->
        </system.webServer>
    

    您无需再在Global.asax 中设置Response.AddHeader

    【讨论】:

      猜你喜欢
      • 2018-11-15
      • 2019-05-20
      • 1970-01-01
      • 2023-01-13
      • 2012-12-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多