ASP.NET 核心中的属性路由不起作用

Attribute Routing in ASP.NET Core not working

我的控制器中有以下代码class

[Route("movies/released/{{year}}/{{month:regex(\d{2}):range(1,12)}}")]
public ActionResult ByReleaseDate(int year, int month)
{
    return Content(year + "/" + month);
}

并且在启动时有如下代码class

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "MoviesByReleaseDate",                    
                pattern: "{controller=Movies}/{action=ByReleaseDate}/{year}/{month}") ;

            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");             

           
        });

我正在尝试进行属性路由,当我输入 URL

https://localhost:44334/movies/released/2022/06

它应该只在页面上显示 2022/06。而是抛出 404“未找到”错误。我在这里做错了什么?我正在使用 .NET Core 5.0

每个参数使用单花括号代替双花括号。

而对于正则表达式,你需要双花括号\d{{2}}否则你会得到异常

[Route("movies/released/{year}/{month:regex(\d{{2}}):range(1, 12)}")]
您还可以为路由中的每个“年”和“月”提供“:int”。

The :int portion of the template constrains the id route values to strings that can be converted to an integer.

更正:

如果您看到 GetInt2Product 样本,

The GetInt2Product action contains {id} in the template, but doesn't constrain id to values that can be converted to an integer. A GET request to /api/test2/int2/abc:

  • Matches this route.
  • Model binding fails to convert abc to an integer. The id parameter of the method is integer.
  • Returns a 400 Bad Request because model binding failed to convertabc to an integer.

路由中未提及会自动转换为参数类型,并处理转换失败的场景

Attribute routing with Http verb attributes