Asp.net core UseStatusCodePages()在请求管道中的位置
我有一个带有承载身份验证的aspnet核心MVC项目(令牌是从另一个api接收的) 我需要重定向到未经授权的请求登录页面,所以我找到了UseStatusCodePages()方法。 奇怪的是,UseStatusCodePages必须放在授权中间件之前:Asp.net core UseStatusCodePages()在请求管道中的位置,asp.net-core,Asp.net Core,我有一个带有承载身份验证的aspnet核心MVC项目(令牌是从另一个api接收的) 我需要重定向到未经授权的请求登录页面,所以我找到了UseStatusCodePages()方法。 奇怪的是,UseStatusCodePages必须放在授权中间件之前: app.UseStatusCodePages(context => { var response = context.HttpContext.Response; if (response.Stat
app.UseStatusCodePages(context =>
{
var response = context.HttpContext.Response;
if (response.StatusCode == (int)HttpStatusCode.Unauthorized ||
response.StatusCode == (int)HttpStatusCode.Forbidden)
{
response.Redirect("/Account/Login");
}
return Task.CompletedTask;
});
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
"default",
"{controller=Home}/{action=Index}/{id?}");
});
我想,UseAuthentication中间件返回401,然后就可以处理它了。那么,如果401代码放在UseAuthentication之前,UseStatusCodePages中间件如何处理它呢?如果我将UseStatusCodePages放在UseAuthorization之后,它将根本不会被调用,这很奇怪。有人能解释这种行为吗?中间件不会在另一个中间件之前或之后运行;相反,中间件在其他中间件周围或内部运行 在您的示例设置中,以下是中间件的执行方式:
Request
| StatusCodePages
| ⮩ (next)
| StaticFiles
| ⮩ (next)
| Routing
| ⮩ (next)
| Authentication
| ⮩ (next)
| Authorization
| ⮩ (next)
| Endpoints
| (serve request)
| ⮨
| ⮨
| ⮨
| ⮨
| ⮨
| ⮨
每个中间件都有机会做一些工作,然后调用管道中的下一个中间件。一旦下一个中间件完成,该中间件在内部中间件完成后就有机会进行一些处理
对于StatusCodePages中间件,它所做的是执行下一个中间件,一旦完成,它将查看生成的状态代码并运行自定义处理程序,该处理程序有机会修改响应
如果您交换订单,那么StatusCodePages中间件将在生成401/403状态代码的中间件中运行,因此无法对其结果进行操作。谢谢。我以为这是一个管道,但实际上是一个调用堆栈
Request
| StatusCodePages
| ⮩ (next)
| StaticFiles
| ⮩ (next)
| Routing
| ⮩ (next)
| Authentication
| ⮩ (next)
| Authorization
| ⮩ (next)
| Endpoints
| (serve request)
| ⮨
| ⮨
| ⮨
| ⮨
| ⮨
| ⮨