Adding X-Frame-Options header to all pages in MVC 4 application

Xaxum picture Xaxum · May 10, 2013 · Viewed 43.7k times · Source

I am trying to add the X-Frame-Options header (with value set to "DENY") into my MVC 4 application. I looked around and it seems this is the cleanest way to add for all pages.

However when I add this code it will not build. With an error on OnResultExecuting of

"no suitable method found to override."

public class XframeOptions : ActionFilterAttribute
{
    public override void OnResultExecuting(
          System.Web.Mvc.ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.AddHeader(
            "X-Frame-Options", "DENY");
    }
}

If this is the cleanest way to do this how can I resolve this error? Is there a better way to handle this in an MVC 4 application?

Answer

robrich picture robrich · Feb 28, 2014

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>