ASP.NET Core 自定义中间件重定向到操作不起作用

mk_*_*_yo 5 http asp.net-core asp.net-core-middleware asp.net-core-webapi

我正在尝试使用自定义中间件来处理 404 错误:

app.Use(async (context, next) =>
{
    await next();
    if (context.Response.StatusCode == 404)
    {
        context.Request.Path = "/error/404";
        await next();
    }
});
Run Code Online (Sandbox Code Playgroud)

但是错误控制器中没有调用所需的操作:

[Route("error")]
public class ErrorController : Controller
{
    public ErrorController()
    {
    }

    [Route("404")]
    public IActionResult PageNotFound()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经检查过是否会像“http:\localhost\error\404”那样直接进行调用,是否会调用它

Fei*_*Han 3

如果可能,您可以尝试使用UseStatusCodePagesWithReExecute 扩展方法来实现您的要求。

app.UseStatusCodePagesWithReExecute("/error/{0}");
Run Code Online (Sandbox Code Playgroud)

此外,在您的自定义中间件代码逻辑中,您可以修改代码以重定向到目标url。

if (context.Response.StatusCode == 404)
{
    //context.Request.Path = "/error/404";

    context.Response.Redirect("/error/404");
    return;
}
Run Code Online (Sandbox Code Playgroud)