【问题标题】:how to add default parameters to attribute routes in asp.net mvc如何将默认参数添加到asp.net mvc中的属性路由
【发布时间】:2018-05-15 17:01:47
【问题描述】:

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

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

到属性路由:

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

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

【问题讨论】:

    标签: c# .net asp.net-mvc attributerouting


    【解决方案1】:

    您可以使用多个 [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;
    }
    

    当您向没有年份的电影/发行发送请求时,默认值用于年份。当您向movies/released/2000 发送请求时,URL 参数会覆盖默认值。

    【讨论】:

      【解决方案2】:

      您可以在属性路由中定义路由约束以仅允许某些值

      [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

      希望对你有帮助

      【讨论】:

      • 像魅力一样工作。我也在寻找同样的东西。
      猜你喜欢
      • 2012-09-12
      • 1970-01-01
      • 2018-10-29
      • 2011-08-01
      • 2019-01-21
      • 2010-11-01
      • 1970-01-01
      • 2023-01-25
      • 2017-07-08
      相关资源
      最近更新 更多