我正在使用 asp.net core 6,在我的 program.cs 中有以下中間件,用于在狀態碼為 404 時重定向用戶。
app.Use(async (ctx, next) =>
{
await next();
if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
{
string originalPath = ctx.Request.Path.Value;
ctx.Items["originalPath"] = originalPath;
ctx.Request.Path = "/error/NotFound404";
await next();
}
});
這一切都很好,但我想清理一下我的 program.cs,所以我決定把這段代碼放在它自己的類中,如下所示:
public class NotFoundMiddleware
{
private readonly RequestDelegate _next;
public NotFoundMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
if (httpContext.Response.StatusCode == 404 && !httpContext.Response.HasStarted)
{
string originalPath = httpContext.Request.Path.Value;
httpContext.Items["originalPath"] = originalPath;
httpContext.Request.Path = "/error/NotFound404";
}
await _next(httpContext);
}
}
public static class NotFoundMiddlewareExtensions
{
public static IApplicationBuilder CheckNotFound(this IApplicationBuilder builder)
{
return builder.UseMiddleware<NotFoundMiddleware>();
}
}
在我的 program.cs
app.CheckNotFound(); // on the same place the upp.Use... was before.
但后來它不再起作用了。
我使用斷點瀏覽了我的代碼。并且在每個請求上都會呼叫 InvokeAsync,問題是httpContext.Response.StatusCode總是回傳200。
uj5u.com熱心網友回復:
在測驗回傳值之前,您的行內中間件呼叫 next。該類僅在之后呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/457089.html
標籤:C# asp.net 核心 asp.net-core-middleware
