1

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

2
  • 2
    Just as a test - try to simplify your routing attribute - use only single curly braces, and simplify the month: [Route("movies/released/{year:int}/{month:int}")] - does it work now? Commented Jun 5, 2022 at 5:51
  • Before I was using app.UseMvc and routes.MapRoute it was throwing error for not two curly braces. With endpoints its working working now. And its working witout int type defined in the url. Can u explain bit further on why we have to use 'int'. And your solution working. Commented Jun 5, 2022 at 6:18

1 Answer 1

2

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)}")]
You may also provide `:int` to each `year` and `month` in the route.

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

Attribute routing with Http verb attributes

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

Comments

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.