默认情况下,我的站点启用了 x-frame-options: SAMEORIGIN 标头。我想将它从特定视图中删除,以便仅将该视图托管在 3rd 方 iFrame 中。
public ActionResult Callback1()
{
// Remove the anti-clickjacking setting
Response.Headers.Remove("X-Frame-Options");
Return View();
}
// Does not remove the header
public ActionResult Callback2()
{
// Try to override the setting
Response.Headers["X-Frame-Options"] = "ALLOW-FROM https://foo.com"
Return View();
}
// Results in x-frame-options: ALLOW-FROM https://foo.com, SAMEORIGIN
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激。
如果您通过在 web.config 中添加customHeaderundersystem.webServer元素启用了 X-Frame-Options 标头,则在您的操作方法中删除此标头将不起作用。因为即使您的代码从响应中删除了标头,IIS 也会在将响应返回给浏览器之前将其添加回来。
对此的一种解决方案是创建一个自定义 HttpModule,它会检查 url 并从特定网页中删除此标头。您可以将此模块注入请求管道。
另一个更简单的方法是从 web.config 中删除设置并启用在代码中添加标头。您可以创建一个动作过滤器来做到这一点。
public class EnableSameOriginHeader : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Response.AddHeader("X-Frame-Options", "SAMEORIGIN");
base.OnActionExecuted(filterContext);
}
}
Run Code Online (Sandbox Code Playgroud)
对于您希望启用此标头的所有操作方法,只需使用此过滤器装饰它即可。
[EnableSameOriginHeader]
public ActionResult Users()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
如果您不想启用此功能,请不要使用此过滤器进行装饰并在其中添加您的自定义标头值。
public ActionResult SpecialView()
{
Response.Headers["X-Frame-Options"] = "ALLOW-FROM https://foo.com";
return View();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2944 次 |
| 最近记录: |