5

I have used two regular expressions, one to limit the first parameter(year) to 4 digits and the second(month) to limit the second parameter to 2 digits.

[Route("movies/released/{year:regex(\\d{4})}/{month:regex(\\d{2}):range(1, 12)}")] public ActionResult ByReleaseDate(int year, int month) { return Content($"{year}/{month}"); } 

This partially works, when I navigate to /movies/released/2017/13 I am shown a 404.

But when I navigate to /movies/released/200017/03 a 404 is not produced.

3 Answers 3

6

Your regex for year matches 4 digits anywhere but doesn't require it to be only 4 digits. You should use

{year:regex(^\\d{4}$)} 

^ and $ mark the start and the end of the string. Also see: Regular expression for specific number of digits

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

Comments

2

I know this is old and has already but answered but I thought sharing might help the visitors. I was watching ASP .Net MVC5 tutorial by Mosh here and found that he has mentioned the correction in Attribute Routing Section. Following worked for me.

[Route("movies/released/{year}/{month:regex(\\d{2}):range(1, 12)}")] 

1 Comment

I am watching the same tutorial but this isn't working for me
1

use {{2}} instead of {2}

In your case this will work [Route("movies/released/{year}/{month:regex(\\d{{2}}):range(1, 12)}")]

explanation: In a route parameter, '{' and '}' must be escaped with '{{' and '}}'.

Comments