Reputation: 63
The regular expression in attribute routing constraint does not seem to be working as expected. Here is a code,
[Route("movies/released/{year}/{month:regex(\\d{{2}})})]
public ActionResult ByReleaseDate(int year, int month)
{ ... }
Here, I am expecting this action will be called if the month value of the URL is exactly 2 digits long. However, when I tested the application on my browser, the month takes any value of length 2 or more digits.
I have done the same thing using Convention Based Routing technique. There it works as expected. Here is the code of Convention Based Routing I used:
endpoints.MapControllerRoute(
name: "ByReleaseDate",
pattern: "movies/released/{year}/{month}",
defaults: new {controller= "Movies", action = "ByReleaseDate"},
constraints: new {month=@"\d{2}});
However, the attribute routing is not working accordingly. I want to know, whether it is a bug or is it designed to work like that.
The tutorial I am following uses Dotnet Framework MVC. The tutorial is old, most probably from 2014.
Here is my development setup:
OS: Ubuntu-mate 21.04
Dotnet Core Version: Dotnet 5.0.7
EDIT 1: Does regex(\\d{{2}})
constraints the URL parameter to be of exactly 2 digits or it constraints the URL parameter to be at least 2 digits long?
Upvotes: 3
Views: 207
Reputation: 765
This worked for me
[Route("movies/released/{year}/{month:regex(\\d{{2}})}")]
Furthermore you can restrict route to contain months in range 1-12 as well like
movies/released/{year}/{month:regex(\\d{{2}}):range(1, 12)}
You can also set limit on year for 4 digits only , currently it is accepting any number of digits.
{year:regex(^\\d{4}$)}
Upvotes: 1