我正在尝试更改此基于约定的路由:
routes.MapRoute(
"MovieByReleaseDate",
"movies/released/{year}/{month}",
new { controller = "Movies", action = "ByReleasedDate" },
);
属性路由:
[Route("movies/released/{year}/{month}")]
但我看不出如何像第一种方式那样定义默认参数。
最佳答案
您可以使用多个 [Route] 属性和可为 null 的参数来实现您的目标。
[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;
}
当您向 movies/released 发送没有年份的请求时,年份将使用默认值。当您向 movies/released/2000 发送请求时,URL 参数会覆盖默认值。
关于c# - 如何在asp.net mvc 中为属性路由添加默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50355699/