【问题标题】:OWIN AuthenticationMiddleware invoked twice per request每个请求调用两次 OWIN AuthenticationMiddleware
【发布时间】:2017-12-30 13:35:52
【问题描述】:

我在使用 owin cookie 身份验证中间件时遇到了问题:

当我将 cookie 身份验证中间件添加到我的 Startup.Configuration 时,我的所有中间件将在每个请求中调用两次,这是我的代码:

public void Configuration(IAppBuilder app)
    {
        app.Use((context, next) =>
        {
            // this code will be executed twice per http request
            return next();
        });

        // my cookie middleware
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
            AuthenticationMode = AuthenticationMode.Active
        });
    }

然后我自己编写了一个中间件,它继承自 AuthenticationMiddleware 并带有空实现,它的工作原理是一样的——我所有的中间件都会在每个请求中调用两次。

当我调试 owin AuthenticationMiddleware 源码时:

 public override async Task Invoke(IOwinContext context)
    {
        AuthenticationHandler<TOptions> handler = CreateHandler();
        await handler.Initialize(Options, context);
        if (!await handler.InvokeAsync())
        {
            await Next.Invoke(context);
        }
        await handler.TeardownAsync();
    }

我发现await Next.Invoke(context); 会导致我的所有中间件再次被调用。

但是当我使用其他中间件(StaticFiles 中间件、Webapi 中间件)时,一切正常。

我是否遗漏了有关 OWIN 或 AuthenticationMiddleware 的内容?

为什么每个请求都会调用我的中间件两次?是设计使然吗?

【问题讨论】:

    标签: .net owin middleware


    【解决方案1】:

    如果您的所有应用程序都在 Owin 中,您应该将此中间件添加到管道的末尾,您的问题应该会消失!

    app.Run(async context =>
    {
        context.Response.StatusCode = 404;
        await context.Response.WriteAsync("404");
    });
    

    这会将请求保留在 owin 上下文中,并且不会到达默认的 IIS 模块。出于某种原因(我不知道是什么!)如果一个请求从 Owin 发出并且没有模块处理它,则 owin 请求将运行两次!!

    【讨论】:

    • 是的,我发现我应该在我最后一个 owin 中间件中处理请求。如果没有中间件处理请求(并且最后一个中间件返回 next(); ),我所有的中间件都将被再次调用。
    猜你喜欢
    • 2015-06-24
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 2018-11-15
    相关资源
    最近更新 更多