MVC5 automatically adds the HTTP header X-Frame-Options with SAMEORIGIN
. This prevents your site from being loaded into an iframe
.
But we can turn this off in Application_Start
in the Global.asax.cs
.
Example
protected void Application_Start()
{
AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
}
Update
I have written a post about this MVC5 prevents your website being loaded in an IFRAME
Try something like this in Global.asax
:
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Remove("X-Frame-Options");
}
EDIT:
Look at answer of Colin Bacon. It is more correct than mine.
In short - don't remove this header if you don't want to run your site in IFRAME because it will open forgery vulnerability. But if you still want to remove it - use AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
in Application_Start
, it is more cleaner way for doing this.
If you want a little more flexibility, here's an ActionAttribute that adds/removes headers based on a whitelist. If the referrer isn't in the whitelist, then the SAMEORIGIN header is left in place. I was going to paste the code, but SO complains about the length.
https://long2know.com/2016/06/asp-net-anti-forgery-xframe-options/
Here is a replacement Extension method for the HtmlHelper
class. It will first clear all X-Frame-Options
headers and then add back a single X-Frame-Options
header normally added by the built-in AntiForgeryToken
method.
This technique respects the SuppressXFrameOptionsHeader
setting, but has the downside of removing all previously added X-Frame-Options
headers, even those with values other than SAMEORIGIN
.
public static MvcHtmlString AntiForgeryTokenSingleHeader(this HtmlHelper html)
{
string token = AntiForgery.GetHtml().ToString();
HttpResponseBase httpResponse = html.ViewContext.HttpContext.Response;
httpResponse.Headers.Remove("X-Frame-Options");
if (!AntiForgeryConfig.SuppressXFrameOptionsHeader)
{
httpResponse.AddHeader("X-Frame-Options", "SAMEORIGIN");
}
return new MvcHtmlString(token);
}
Personally, I don't think it's a good idea to disable the X-Frame-Options across the whole site.I've created an ASP.NET MVC filter which removes this header and I simply apply this filter to the portions of the site that are used in iFrames e.g. widgets.
public class AllowDifferentOrigin : ActionFilterAttribute, IActionFilter
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.Headers.Remove("X-Frame-Options");
base.OnResultExecuted(filterContext);
}
}
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