简体   繁体   中英

ASP.NET MVC 5: Define route order across controllers (RouteAttribute)

The RouteAttribute("abc", Order = 2) ordering only seems to be respected within a controller: when the following methods are defined in the same controller I get the expected behavior, ie, Method1 takes priority, Method2 is never invoked.

[Route("abc", Order = 1)]
public ActionResult Method1() { ... }

[Route("abc", Order = 2)]
public ActionResult Method2() { ... }

If I define those methods in two separate controllers I get an ambiguous route exception: InvalidOperationException: Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL. InvalidOperationException: Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.

Is it possible to define the order across controllers using attribute routing?

Edit 1 : It seems that even routes that would have an implicit ordering within one controller are ambiguous when spread over multiple controllers. The following would be okay within one controller (literal before wildcard), but throws an exception if placed into different controllers.

[Route("details/abc")]
[Route("details/{product}")]

This makes me that it is by design to keep controllers focused and force similar routes to be defined in the same controller.

Edit 2 :

These are the routes I actually want to use. I want to put them into different controllers, because they do different things. They differ by the prefix.

[Route("reactive/monitor")]
[Route("{tier}/monitor")]

You have no constraints upon the route parameters, for your second route. If you were to define the route as [Route("{tier:int}/monitor")] you might not have the ambiguity. Alternatively, you can add a regex to the routes, to make them exclusive, something like {tier:regex(^(?!reactive))?} would let you resolve this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM