ASP.Net Core:X-Frame-Options奇怪的行为 [英] ASP.Net Core: X-Frame-Options strange behavior
问题描述
我需要从一些应为iframe呈现内容的操作中删除X-Frame-Options: SAMEORIGIN
标头.只要默认情况下将其添加到请求中,我就会在Startup.cs
:services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = false);
中将其禁用.然后我写了一个简单的中间件:
I need to remove X-Frame-Options: SAMEORIGIN
header from some of my actions which should render a content for an iframe. As long as it is added to requests by default I disabled it in Startup.cs
: services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = false);
. Then I wrote a simple middleware:
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
await next();
});
回答跨域请求所需的操作均以结果过滤器属性修饰:
Actions needed to answer to cross-domain requests are decorated with result filter attribute:
public class SuppresXFrameOptionFilter : ResultFilterAttribute
{
public override async Task OnResultExecutionAsync(ResultExecutingContext context,
ResultExecutionDelegate next)
{
context.HttpContext.Response.Headers.Remove("X-Frame-Options");
await next();
}
}
奇怪的来了.第一个跨域请求失败,因为尽管过滤器最终运行正常,但响应中仍然存在X-Frame-Options: SAMEORIGIN
(我在中间件中的next()
之后检查了它-重新出现了标头).如果我按F5键,标题将不再在响应中,并且一切正常.仅使用X-Frame-Options
标头会发生这种情况,正确删除了一个自定义标头.
是什么使被删除的X-Frame-Options
再次出现在响应中?
Here comes the weiredness. First cross-domain request fails because despite the filter works as expected in the end the X-Frame-Options: SAMEORIGIN
is still present in the response (I checked it after next()
in the middleware - the header reappeared). If I press F5 the header is no longer in the response and everything works as it should. That happens only with X-Frame-Options
header, a custom one is removed correctly.
What makes the X-Frame-Options
which has been removed appear in a response again?
推荐答案
I would say on the first request Antiforgery saves the cookie which means it also tries to set the X-Frame-Options
header.
如果您想在Antiforgery中禁用该标头并自己手动处理,则需要将SuppressXFrameOptionsHeader
设置为true ;)
If you want to disable that header in Antiforgery and manually handle it yourself, what you want is setting SuppressXFrameOptionsHeader
to be true ;)
services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = true);
这篇关于ASP.Net Core:X-Frame-Options奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!