7

I am trying to change this convention based route:

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

to attribute route:

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

but I can't see how I can define default parameters like in the first way.

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

worked great - only thing I stumbled across is that it's important that the parameter is marked as nullable, providing a default value is not sufficient. Kinda makes sense if you think about it, I think default values are used at the call site to fill in the blanks. Anyway, something to watch out for
2

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

1 Comment

Works like a charm. I was searching for the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.