.net core 有多个中间件时 怎么拦截404让其立即返回
如图 我的代码现在状况是
会一直往下走 走完所有的中间件才会 去校验404 有什么办法在404的时候立即返回
app.UseStatusCodePages(async context =>
{
if (context.HttpContext.Response.StatusCode == 404)
{
await context.HttpContext.Response.WriteAsync("404 Not Found");
}
});
你可以在这种情况下想办法跳过中间件。在 .NET Core 中,可以通过调用中间件中的 next() 方法来跳过消息中间件。
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
...
await _next(context);
}
}