首页 > 解决方案 > 属性路由不是现有路由

问题描述

我有一个带有属性路由的项目,例如:

[Route("home")]
public class HomeController : Controller
{
     [HttpPost]
     public IActionResult Post(int id)
     {
     }

     [HttpGet]
     public IActionResult Get()
     {
     }
}

现在我想捕获所有没有指定路由的 Get/Post/Put 请求。所以我可以返回一个错误,重定向到主页等等。是否可以使用 AttributeRouting 或者我应该在启动时使用常规路由?“不存在”的路线在那里看起来如何?

标签: c#controllerrouting.net-coreattributerouting

解决方案


默认情况下,服务器返回 404 HTTP 状态代码作为对未由任何中间件处理的请求的响应(属性/约定路由是 MVC 中间件的一部分)。

一般来说,你总是可以做的是在管道的开头添加一些中间件来捕获所有带有 404 状态代码的响应并执行自定义逻辑或更改响应。

在实践中,您可以使用 ASP.NET Core 提供的称为StatusCodePages中间件的现有机制。您可以通过以下方式将其直接注册为原始中间件

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()

中间件支持几种扩展方法,如下所示(区别在本文中有很好的解释):

app.UseStatusCodePages("/error/{0}");
app.UseStatusCodePagesWithRedirects("/error/{0}");
app.UseStatusCodePagesWithReExecute("/error/{0}");

where"/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)

推荐阅读