gpt4 book ai didi

c# - 如何在asp.net mvc 中为属性路由添加默认参数

转载 作者:行者123 更新时间:2023-11-30 23:02:40 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com