如何在 asp.net mvc 中将默认参数添加到属性路由
how to add default parameters to attribute routes in asp.net mvc
我正在尝试更改此基于约定的路由:
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 参数会覆盖默认值。
您可以在属性路由中定义路由约束以仅允许某些值
[Route("movies/released/{year:regex(2015|2016)}/{month:regex(\d{2}):range(1,12)}")]
public ActionResult ByReleasedDate(int year, int month)
{
return Content($"year {year} and month {month}");
}
通过使用 {year:regex(2015|2016)}
它只允许 2015 或 2016 年参数
通过使用 {month:regex(\d{2}):range(1,12)}
它只允许 2 位数字表示月份,范围从 1 到 12
希望对您有所帮助
我正在尝试更改此基于约定的路由:
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 参数会覆盖默认值。
您可以在属性路由中定义路由约束以仅允许某些值
[Route("movies/released/{year:regex(2015|2016)}/{month:regex(\d{2}):range(1,12)}")]
public ActionResult ByReleasedDate(int year, int month)
{
return Content($"year {year} and month {month}");
}
通过使用 {year:regex(2015|2016)}
它只允许 2015 或 2016 年参数
通过使用 {month:regex(\d{2}):range(1,12)}
它只允许 2 位数字表示月份,范围从 1 到 12
希望对您有所帮助