cod*_*urn 14 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.HttpContext.Response.AddHeader("X-FRAME-OPTIONS", "SAMEORIGIN");
}
}
Run Code Online (Sandbox Code Playgroud)
查看Fiddler,我可以看到从Web服务器返回的视图包含此标题.但是,静态文件(例如JavaScript)在HTTP响应中不包含此标头.
如何让ASP.NET MVC也将此过滤器应用于Web服务器返回的任何静态文件?
ram*_*ilu 16
为网站的所有内容设置标头的一种方法是web.config
.该customHeaders
部分将确保所有文件和响应都包含此标头.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-FRAME-OPTIONS" value="SAMEORIGIN" />
</customHeaders>
</httpProtocol>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
另一种选择是创建自定义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");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后将它们注册web.config
为如下所示 -
<system.webServer>
<modules>
<add name="CustomHeaderModule" type="MvcApplication1.Modules.CustomOriginHeader" />
</modules>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
如果您希望对每个请求(静态或动态请求)执行此操作,您可能应该通过 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>
Run Code Online (Sandbox Code Playgroud)
如果您可以直接访问 IIS,则也可以使用 UI 进行设置。