属性路由不是现有路由



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

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

现在,我想捕获所有没有指定路由的get/post/put请求。因此,我可以将错误返回,重定向到主页和此类内容。是否可以使用属性来处理,还是我应该在启动中使用常规路由?"不存在"路线将如何看?

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

通常,您总是可以做的是在管道开头添加一些中间件,以使用404状态代码捕获所有响应并进行自定义逻辑或更改响应。

实际上,您可以使用称为StatusCodePages中间件的ASP.NET核心提供的现有机制。您可以通过

将其直接注册为原始中间件
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}");

其中 "/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)

最新更新