how to add default parameters to attribute routes in asp.net mvc

淺唱寂寞╮ 提交于 2019-12-02 01:11:57
Steve Perkins

You can use multiple [Route] attributes coupled with nullable parameters to achieve your goal.

[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;
}

When you send a request to movies/released without a year, the default value is used for the year. When you send a request to movies/released/2000, the URL parameter overrides the default value.

You can define route constriants in attributte routing to allow only some value

[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}");
    }

by using {year:regex(2015|2016)} it allows only 2015 or 2016 in year parameter

by using {month:regex(\\d{2}):range(1,12)} it allows only 2 digit for month and range from 1 to 12

Hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!