Adding X-Frame-Options header to all pages in MVC 4 application
You are getting this error because you are using the wrong method name instead of OnResultExecuting
use OnResultExecuted
.
You should write your method like this:
public class XframeOptionsFilter : System.Web.Mvc.ActionFilterAttribute
{
public override void OnResultExecuted(System.Web.Mvc.ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.AddHeader("x-frame-options", "Deny");
}
}
There is another way to do that. create a custom HttpModule like below:
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");
}
}
then register this module in web.config
<modules >
<add name ="XframeOptions" type="your module's full type info"/>
</modules>
Make sure you inherit from the correct class
:
public class XframeOptions : System.Web.Mvc.ActionFilterAttribute
In ASP.NET MVC 4 there's the Web API which has different namespace and since you haven't explicitly specified the namespace I guess that the compiler is picking the wrong class:
System.Web.Http.Filters.ActionFilterAttribute
There's no need for a custom HttpModule or ActionFilter if you need it for every page. https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options details a much simpler solution:
To configure IIS to send the X-Frame-Options header, add this your site's Web.config file:
<system.webServer>
<!-- ... -->
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="SAMEORIGIN" />
</customHeaders>
</httpProtocol>
<!-- ... -->
</system.webServer>