我正在尝试在all
个请求的响应标头中添加内容安全策略标头。所以我创建了OWIN中间件
public class SecurityHeaderMiddleware
{
private readonly INonceService _nonceService = null;
private readonly Func<Task> _next;
public SecurityHeaderMiddleware(Func<Task> next, INonceService nonceService)
{
_nonceService = nonceService;
_next = next;
}
public async Task Invoke(IOwinContext context)
{
// do something here to add CSP header in context.Response.Headers
await _next.Invoke();
}
然后为每个请求调用我的中间件,我根据建议here
在startup.csbefore PostResolveCache
阶段标记中注册我的中间件
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use((context, next) =>
{
var nonceService = ServiceLocator.Current.GetInstance<INonceService>();
var middleware = new SecurityHeaderMiddleware(next, nonceService);
return middleware.Invoke(context);
});
app.UseStageMarker(PipelineStage.PostResolveCache);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// set options here
});
MvcHandler.DisableMvcResponseHeader = true;
}
}
但是,我的中间件仅针对实际页面或任何ajax请求进行调用,当浏览器向javascript,CSS或图像发出请求时,不会被调用
如何为所有请求调用自定义中间件?如果不是OWIN中间件那么我可以选择为asp.net中的所有请求添加标头
答案 0 :(得分:0)
我想应该设置PostAuthorize
stage marker来处理静态内容请求。它甚至在链接问题的评论中提到:
app.Use(...);
app.UseStageMarker(PipelineStage.PostAuthorize);