I have the following code in my controller class
[Route("movies/released/{{year}}/{{month:regex(\\d{2}):range(1,12)}}")]
public ActionResult ByReleaseDate(int year, int month)
{
return Content(year "/" month);
}
And have the following code in the startup class
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "MoviesByReleaseDate",
pattern: "{controller=Movies}/{action=ByReleaseDate}/{year}/{month}") ;
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
I am trying to do attribute routing where as when I type in the URL
https://localhost:44334/movies/released/2022/06
it should just display 2022/06 on page. But instead its throwing 404 "not found" error. What am I doing wrong here? I'm using .NET Core 5.0
CodePudding user response:
Use single curly brace instead of dual curly braces for each parameter.
While for the regex, you need dual curly braces \\d{{2}}
otherwise you will get the exception
[Route("movies/released/{year}/{month:regex(\\d{{2}}):range(1, 12)}")]
The :int portion of the template constrains the id route values to strings that can be converted to an integer.
Correction:
If you see the GetInt2Product
sample,
The GetInt2Product action contains {id} in the template, but doesn't constrain id to values that can be converted to an integer. A GET request to /api/test2/int2/abc:
- Matches this route.
- Model binding fails to convert abc to an integer. The id parameter of the method is integer.
- Returns a 400 Bad Request because model binding failed to convertabc to an integer.
It will automatically to convert to parameter type without mentioning in the route, and handling the scenario when failed to convert