【问题标题】:ASP.NET MVC: Programmatically set HTTP headers on static contentASP.NET MVC:以编程方式在静态内容上设置 HTTP 标头
【发布时间】:2016-01-22 17:55:56
【问题描述】:

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

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

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

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

【问题讨论】:

  • 这与 Web API 过滤器无关 @DeblatonJean-Philippe

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

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

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

另一种选择是创建自定义HttpModule,如下所示。这样,您可以更好地控制需要附加标头的文件和内容。

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注册如下图——

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

【讨论】:

  • 我曾考虑过这样做,但如果我有一个场景,我想只为 某些 静态文件添加特定的标头。
  • 我还用编程方式更新了我的答案来添加标题,看看吧。
【解决方案2】:

如果您希望在每个请求(静态或动态请求)上都执行此操作,您可能应该通过 IIS(Web 服务器)进行设置。以下是您可以实现此目的的不同方法的一些详细信息 - http://www.iis.net/configreference/system.webserver/httpprotocol/customheaders

简而言之,您可以在 web.config 文件中执行此操作

<configuration>
   <system.webServer>
      <httpProtocol>
         <customHeaders>
            <add name="X-Custom-Name" value="MyCustomValue" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
</configuration>

如果您可以直接访问 IIS,也可以使用 UI 进行设置。

【讨论】:

    猜你喜欢
    • 2013-01-27
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2017-11-22
    • 2012-06-26
    • 2012-07-11
    相关资源
    最近更新 更多