【问题标题】:Attribute Routing not existing routes属性路由不是现有路由
【发布时间】:2018-10-05 12:07:45
【问题描述】:

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

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

     [HttpGet]
     public IActionResult Get()
     {
     }
}

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

【问题讨论】:

    标签: c# controller routing .net-core attributerouting


    【解决方案1】:

    默认情况下,服务器返回 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-10
      • 2021-09-04
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2017-03-24
      • 2013-11-02
      • 2014-04-15
      相关资源
      最近更新 更多