Search code examples
c#asp.net-mvcasp.net-mvc-4http-headersx-frame-options

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


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?


Solution

  • 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