我正在尝试更改此基于约定的路由:

routes.MapRoute(
    "MovieByReleaseDate",
    "movies/released/{year}/{month}",
    new { controller = "Movies", action = "ByReleasedDate" },
);


归因于路线:

[Route("movies/released/{year}/{month}")]


但是我看不到如何像第一种方式那样定义默认参数。

最佳答案

您可以结合使用多个[Route]属性和可为空的参数来实现您的目标。

[HttpGet]
[Route("movies/released/")]
[Route("movies/released/{year}")]
[Route("movies/released/{year}/{month}")]
public string Test(int? year = 2018, int? month = 1)
{
    return "The year is " + year;
}


当您向电影/不带年份的电影发送请求时,该年份将使用默认值。将请求发送到movie / released / 2000时,URL参数将覆盖默认值。

09-07 00:46