MVC 5 prevents access to content via Iframe

后端 未结 5 806
灰色年华
灰色年华 2020-12-01 12:01

Ever since the upgrade from MVC4 to MVC5, I have noticed an extra server header added to my web pages:

X-Frame-Options: SAMEORIGIN

I understand security bene

5条回答
  •  一向
    一向 (楼主)
    2020-12-01 12:24

    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);
    }
    

提交回复
热议问题