1
votes

TL;DR;
How can i have "http://localhost/posts/1" be routed to public IActionResult Index(int? id) on PostsController?

Semi-Long Version:
My routes are defined as:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "posts",
        template: "Posts/{id:int?}",
        defaults: new { controller = "Posts", action = "Index" });
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id:int?}");
});

my posts controller is:

[Route("posts")]
public class PostsController : Controller
{
    public IActionResult Index(int? id)
    {
        return View();
    }
}

the problem is that "http://localhost:5432/posts" works ok BUT "http://localhost:5432/posts/1" does route properly...

Edit1:

public class PostsController : Controller
{
    [Route("Posts/{id:int?}"
    public IActionResult Index(int? id)
    {
        return View();
    }
}

works... but i would not like to have routes handled for each action... this is supposed to be a very large system... things might get crazy like this...

1
Does it work if you use a string instead of int?. You could convert the string to an int in code using int.TryParseKen Tucker
@KenTucker no... same problem... i also fixed the route removing the int constraintLeonardo

1 Answers

2
votes

Since you decorated controller with Route attribute, the rules that you defined in routes table will not be actually used. Here is a quote from the article Routing to Controller Actions:

Actions are either conventionally routed or attribute routed. Placing a route on the controller or the action makes it attribute routed.

So to fix your problem, just remove [Route("posts")] attribute from PostsController.