【发布时间】: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