MVC5:您如何覆盖或更改特定视图的标题?

Bil*_*ara 3 asp.net-mvc

默认情况下,我的站点启用了 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)

任何帮助,将不胜感激。

Shy*_*yju 6

如果您通过在 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)

  • 谢谢。我接受了您的回答,但我翻转了此解决方案并创建了 2 个过滤器。我在整个站点上启用了一个应用 SAMEORIGIN 保护,另一个在必要时将其删除。这样,如果我忘记在某处应用它,我不会让该网站易受攻击。 (2认同)