我正在尝试在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();
}
然后为每个请求调用我的中间件,我按照这里before PostResolveCache
的建议在 startup.cs 阶段标记中注册我的中间件
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 中为所有请求添加标头的选项是什么