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?
Double-click the HTTP Response Headers icon in the feature list in the middle. In the Actions pane on the right side, click Add. In the dialog box that appears, type X-Frame-Options in the Name field and type SAMEORIGIN in the Value field. Click OK to save your changes.
You can then send a X-Frame-Options response HTTP header with the value: "Allow-From ip-address", where ip address is the remote ip address that is trying to embed content on your server. This will allow your website to be embedded by all websites that are accessed using an ip address from the browser.
When X-Frame-Options Header is not set your application pages can be embedded within any other website with no restrictions, e.g. to create a malicious page with your original content augmented with dangerous fragments including phishing attempts, ads, clickjacking code, etc.
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>
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 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With