OWIN AuthenticationMiddleware每个请求调用两次

问题描述 投票:1回答:1

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

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

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个回答
0
投票

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

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

这将使请求保留在owin上下文中,并且它将无法访问默认的IIS模块。出于某种原因(我不知道是什么!)如果请求离开Owin并且没有模块处理它,那么owin请求会运行两次!!

© www.soinside.com 2019 - 2024. All rights reserved.