【问题标题】:OWIN middleware does not get invoked for all requests不会为所有请求调用 OWIN 中间件
【发布时间】:2022-04-07 16:08:52
【问题描述】:

我正在尝试在 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.cs before 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 中为所有请求添加标头的选项是什么

【问题讨论】:

    标签: asp.net asp.net-mvc owin owin-middleware


    【解决方案1】:

    我注意到 owin 中间件仅被 MVC 处理程序服务的请求调用。

    答案是添加捕获所有路由,因此所有内容都路由到 mvc 处理程序。

    【讨论】:

      【解决方案2】:

      我猜PostAuthorize stage marker 应该设置为处理静态内容请求。甚至在链接问题的 cmets 中也提到了它:

      app.Use(...);
      
      app.UseStageMarker(PipelineStage.PostAuthorize);
      

      【讨论】:

        猜你喜欢
        • 2016-03-04
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2017-09-27
        • 1970-01-01
        • 2016-12-14
        • 2016-03-27
        • 1970-01-01
        相关资源
        最近更新 更多