默认情况下,服务器返回 404 HTTP 状态码作为对未由任何中间件处理的请求的响应(属性/约定路由是 MVC 中间件的一部分)。
一般来说,您始终可以做的就是在管道的开头添加一些中间件,以捕获所有带有 404 状态码的响应并执行自定义逻辑或更改响应。
在实践中,您可以使用 ASP.NET Core 提供的现有机制 StatusCodePagesmiddleware。您可以通过
直接将其注册为原始中间件
public void Configure(IApplicationBuilder app)
{
app.UseStatusCodePages(async context =>
{
context.HttpContext.Response.ContentType = "text/plain";
await context.HttpContext.Response.WriteAsync(
"Status code page, status code: " +
context.HttpContext.Response.StatusCode);
});
//note that order of middlewares is importante
//and above should be registered as one of the first middleware and before app.UseMVC()
中间件支持多种扩展方法,如下所示(区别在this article中有很好的解释):
app.UseStatusCodePages("/error/{0}");
app.UseStatusCodePagesWithRedirects("/error/{0}");
app.UseStatusCodePagesWithReExecute("/error/{0}");
其中"/error/{0}" 是一个路由模板,可以是您需要的任何东西,它的{0} 参数将代表错误代码。
例如要处理 404 错误,您可以添加以下操作
[Route("error/404")]
public IActionResult Error404()
{
// do here what you need
// return custom API response / View;
}
或一般操作
[Route("error/{code:int}")]
public IActionResult Error(int code)