【问题标题】:Removing "X-Frame-Options" header for a specific controller only仅删除特定控制器的“X-Frame-Options”标头
【发布时间】:2016-05-29 17:17:22
【问题描述】:

我正在尝试使用以下方法仅删除特定控制器操作的“X-Frame-Options”标头:

protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
    filterContext.HttpContext.Response.Headers.Remove("X-Frame-Options");
    base.OnResultExecuting(filterContext);
}

但是,这似乎根本不起作用。我可以让它在我的网站上运行的唯一方法是将此代码添加到下面的 global.asax 中。我很确定我错过了 ASP.NET MVC / IIS 管道中允许我覆盖该标头的 IIS 设置的正确步骤。这可能吗?

protected void Application_EndRequest()
{
    Response.Headers.Remove("X-Frame-Options");
}

至于我为什么要这样做,我正在构建一个小部件,用户将能够通过使用 iframe 在他们的个人网站上使用它,但允许他们将信息发回我们的网站。我意识到关闭此标头存在安全隐患,虽然我欢迎有关如何减轻这些风险的任何建议,但我只想知道我的要求是否可行。

【问题讨论】:

    标签: iframe asp.net-mvc-5 x-frame-options


    【解决方案1】:

    OnResultExecuting 在 MVC 生命周期中发生得太早。标题尚未设置。

    你需要的是 OnResultExecuted 方法,它在 View 被渲染之后运行。

    以下是您为要查找的内容编写过滤器类的方法:

    using System.Web.Mvc;
    
    namespace Test.Filters
    {
        public class RemoveXFrameOptionsAttribute : ActionFilterAttribute
        {
            public override void OnResultExecuted(ResultExecutedContext filterContext)
            {
                filterContext.HttpContext.Response.Headers.Remove("X-Frame-Options");
                base.OnResultExecuted(filterContext);
            }
        }
    }
    

    然后使用它,装饰你想要这个过滤器应用的任何控制器或动作。

    [RemoveXFrameOptions]
    public class TestController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
    

    public class TestController : Controller
    {
        [RemoveXFrameOptions]
        public ActionResult Index()
        {
            return View();
        }
    }
    

    【讨论】:

    • 我尝试了同样的方法,但似乎没有用。此外,在删除之前对filterContext.HttpContext.Response.Headers 进行了快速观察,但只有两个标题存在ServerX-AspNetMvc-Version。有什么想法吗?
    • 我和 sitecore 一起尝试过,效果很好!
    猜你喜欢
    • 2015-09-19
    • 1970-01-01
    • 2018-03-10
    • 2017-06-13
    • 2013-11-16
    • 2019-03-07
    • 1970-01-01
    • 2019-03-15
    • 2019-10-19
    相关资源
    最近更新 更多