将X-Frame-Options标头添加到MVC 4应用程序中的所有页面

时间:2013-05-10 14:13:10

标签: c# asp.net-mvc asp.net-mvc-4 http-headers x-frame-options

我正在尝试将X-Frame-Options标头(值设置为“DENY”)添加到我的MVC 4应用程序中。我环顾四周,似乎this是为所有页面添加最简洁的方法。

然而,当我添加此代码时,它将无法构建。 <{1}}

时出错
  

“找不到合适的方法来覆盖。”

OnResultExecuting

如果这是最干净的方法,我该如何解决此错误?在MVC 4应用程序中有更好的方法来处理它吗?

6 个答案:

答案 0 :(得分:121)

如果您需要每个页面都不需要自定义HttpModule或ActionFilter。 https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options详细介绍了一个更简单的解决方案:

要配置IIS以发送X-Frame-Options标头,请将此站点的Web.config文件添加到该文件中:

<system.webServer>
  ...

  <httpProtocol>
    <customHeaders>
      <add name="X-Frame-Options" value="SAMEORIGIN" />
    </customHeaders>
  </httpProtocol>

  ...
</system.webServer>

答案 1 :(得分:14)

确保您继承correct class

public class XframeOptions : System.Web.Mvc.ActionFilterAttribute

在ASP.NET MVC 4中,Web API具有不同的命名空间,因为您没有明确指定命名空间,我猜编译器选择了错误的类:

System.Web.Http.Filters.ActionFilterAttribute

答案 2 :(得分:6)

还有另一种方法可以做到这一点。创建一个自定义的HttpModule,如下所示:

    public class XframeOptionsModule : IHttpModule
{
    public void Dispose()
    {

    }

    public void Init(HttpApplication context)
    {
        context.PreSendRequestHeaders += this.OnPreSendRequestHeaders;
    }
    private void OnPreSendRequestHeaders(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("x-frame-options", "Deny");
    }
}

然后在web.config中注册此模块

    <modules >
        <add name ="XframeOptions" type="your module's full type info"/>
    </modules>

答案 3 :(得分:4)

您收到此错误的原因是您使用了错误的方法名称,而不是OnResultExecuting使用OnResultExecuted。 你应该写这样的方法:

public class XframeOptionsFilter : System.Web.Mvc.ActionFilterAttribute
{
    public override void OnResultExecuted(System.Web.Mvc.ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.AddHeader("x-frame-options", "Deny");
    }
}

答案 4 :(得分:1)

NWebsec允许您通过web.config,OWIN中间件和/或MVC过滤器属性设置此安全标头和其他安全标头:https://github.com/NWebsec/NWebsec/wiki

免责声明:我是该项目的维护者。

答案 5 :(得分:0)

要向所有MVC应用添加拒绝“x-frame-options”标头,您可以执行以下操作以避免Clickjacking攻击。

using System;
using System.Web;

namespace Demo.Website.Modules
{
    public class XfoHeaderModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += ContextPreSendRequestHeaders;
        }

        public void Dispose()
        {
        }

        private void ContextPreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Headers.Add("X-Frame-Options", "Deny");
        }
    }
}

将以下内容添加到web.config

  <system.webServer>
    <modules>
      <add name="XfoHeader" type="Demo.Website.Modules.XfoHeaderModule" />
    </modules>
  </system.webServer>

enter image description here