ASP.NET MVC:以编程方式在静态内容上设置HTTP标头 [英] ASP.NET MVC: Programmatically set HTTP headers on static content

查看:73
本文介绍了ASP.NET MVC:以编程方式在静态内容上设置HTTP标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET应用程序,其过滤器连接到RegisterGlobalFilters中,该过滤器执行以下操作:

I have an ASP.NET application with a filter wired up in RegisterGlobalFilters that performs the following:

public class XFrameOptionsAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(System.Web.Mvc.ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.AddHeader("X-FRAME-OPTIONS", "SAMEORIGIN");
    }
}

在Fiddler中,我可以看到从Web服务器返回的视图包括此标头.但是,静态文件(例如JavaScript)不会在HTTP响应中包含此标头.

Looking in Fiddler, I can see that views returned from the webserver include this header. Static files however, such as JavaScript do not include this header in the HTTP response.

如何获取ASP.NET MVC并将此过滤器也应用于Web服务器返回的任何静态文件?

How do I get ASP.NET MVC to also apply this filter to any static files the web server returns?

推荐答案

为网站的所有内容设置标题的一种方法是在web.config中. customHeaders部分将确保所有文件和响应都包含此标头.

One way to set headers for all the content of site is in web.config. The customHeaders section will make sure that this header is included for all files and responses.

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-FRAME-OPTIONS" value="SAMEORIGIN" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

另一个选择是创建自定义HttpModule,如下所示.这样,您可以对需要附加标题的文件和内容进行更多控制.

Another option is to create custom HttpModule as shown below. This way you have more control on the files and content to which headers needs to be appended.

namespace MvcApplication1.Modules
{
    public class CustomOriginHeader : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }

        public void Dispose() { }

        void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            // For example - To add header only for JS files
            if (HttpContext.Current.Request.Url.ToString().Contains(".js"))
            {
                HttpContext.Current.Response.Headers.Add("X-FRAME-OPTIONS", "SAMEORIGIN");
            }
        }
    }
}

然后将它们注册到web.config中,如下所示-

And then register them in web.config as shown below -

  <system.webServer>
     <modules>
        <add name="CustomHeaderModule" type="MvcApplication1.Modules.CustomOriginHeader" />
     </modules>
  </system.webServer>

这篇关于ASP.NET MVC:以编程方式在静态内容上设置HTTP标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆