中间件在program.cs中起作用,但在移动到自己的类中时不起作用
我正在使用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.cs a a一点,所以我决定将此代码放在这样的类中:
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
。
I'm using asp.net core 6, in my program.cs I have the following middleware, which is used to redirect the user when the statuscode is 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();
}
});
This all works fine, but I want to clean up my program.cs a bit, so I decided to put this code in it's own class like this:
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>();
}
}
And in my program.cs
app.CheckNotFound(); // on the same place the upp.Use... was before.
But then it doesn't work anymore.
I went through my code using breakpoints. and the InvokeAsync gets called on each request,
The problem is that the httpContext.Response.StatusCode
always returns 200
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

在测试返回值之前,您的内联中间件接下来打电话。班级仅在接下来打电话。
Your inline middleware calls next before testing the return value. The class only calls next after.