3

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?

1
  • Please check my answer and try , it should work for you . Please mark my answer helpful if it works. Commented Jun 10, 2021 at 5:51

1 Answer 1

1

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}$)}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the work around. I am know this one. I just wanted to know what does regex(\\d{{2}}) do? Does it constraints the URL parameter to be of exactly 2 digits or it constraints the URL parameter to be at least 2 digits long? Thank you.
At least 2 digits and maximum can be any so that's why I asked to use range.
Please mark my answer as helpful if it worked for you
Can you please accept the answer if it worked for you
Thanks your answer. I was waiting for some more responses...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.