doublnt
doublnt

Reputation: 571

How to handle two route and direct to one Action in .NET-Core Mvc

Here is my route rules in Startup.cs

routes.MapRoute(
                    name: "UnsolvedTagspecial",
                    template: "user/undo/{t}",
                    defaults: new { Controller = "user", action = "undo" }
                    );

routes.MapRoute(
                    name: "UnsolvedTag",
                    template: "user/{t}/undo",
                    defaults: new { Controller = "user", action = "undo" }
                    );

And here is my action in Controller:

//Controller:
public async Task<ActionResult> undo(string t)
{
    //   .....
}

It confuse me, who can tell me why ?

Upvotes: 0

Views: 693

Answers (1)

Usman
Usman

Reputation: 4703

this is because you have to set routes from most specific to most generic. i guess your routes will be like this

 routes.MapRoute(
                   name: "default",
                   template: "{controller=Home}/{action=Index}/{id?}");

routes.MapRoute(
                    name: "UnsolvedTagspecial",
                    template: "user/undo/{t}",
                    defaults: new { Controller = "user", action = "undo" }
                    );

routes.MapRoute(
                    name: "UnsolvedTag",
                    template: "user/{t}/undo",
                    defaults: new { Controller = "user", action = "undo" }
                    );

so when you enter http://localhost:17623/user/undo/111 it hits the first route which expects 111 to be id but when it goes to action the parameter expects string t. so you should place routes like this

routes.MapRoute(
                    name: "UnsolvedTagspecial",
                    template: "user/undo/{t}",
                    defaults: new { Controller = "user", action = "undo" }
                    );

routes.MapRoute(
                    name: "UnsolvedTag",
                    template: "user/{t}/undo",
                    defaults: new { Controller = "user", action = "undo" }
                    );
routes.MapRoute(
                   name: "default",
                   template: "{controller=Home}/{action=Index}/{id?}");

from most specific to most generic

Upvotes: 3

Related Questions