1

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...

2
  • Does it work if you use a string instead of int?. You could convert the string to an int in code using int.TryParse Commented Mar 3, 2018 at 14:36
  • @KenTucker no... same problem... i also fixed the route removing the int constraint Commented Mar 3, 2018 at 14:38

1 Answer 1

2

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.