Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET MVC:以编程方式在静态内容上设置HTTP头_C#_Asp.net_Asp.net Mvc_Asp.net Mvc 4 - Fatal编程技术网

C# ASP.NET MVC:以编程方式在静态内容上设置HTTP头

C# ASP.NET MVC:以编程方式在静态内容上设置HTTP头,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,我有一个ASP.NET应用程序,其过滤器连接在RegisterGlobalFilters中,执行以下操作: public class XFrameOptionsAttribute : ActionFilterAttribute { public override void OnResultExecuting(System.Web.Mvc.ResultExecutingContext filterContext) { filterContext.HttpContex

我有一个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中,我可以看到从Web服务器返回的视图包含此标题。但是,静态文件(如JavaScript)在HTTP响应中不包含此头


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

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

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-FRAME-OPTIONS" value="SAMEORIGIN" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
然后在
web.config
中注册它们,如下所示-

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

如果您希望对每个请求(静态或动态请求)执行此操作,您可能应该通过IIS(web服务器)进行设置。以下是实现这一目标的不同方法的一些细节-

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

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


如果你可以直接访问IIS,你也可以使用UI来设置它。

这与web API过滤器@DeblatonJean Philipper无关我已经考虑过这样做,但是如果我有一个场景,我只想在某些静态文件中添加一个特定的头。我还用编程方式更新了我的答案来添加头,过来看。
<configuration>
   <system.webServer>
      <httpProtocol>
         <customHeaders>
            <add name="X-Custom-Name" value="MyCustomValue" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
</configuration>