简体   繁体   English

ASP.NET MVC 5:跨控制器定义路由顺序(RouteAttribute)

[英]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. RouteAttribute("abc", Order = 2)只订购似乎是在控制器内推崇:当在同一个控制器定义以下方法,我得到预期的行为,即Method1的优先级, Method2则永远不会调用。

[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. 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. 编辑1 :似乎即使在一个控制器中具有隐式排序的路由在分布在多个控制器上时也是不明确的。 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 : 编辑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. 如果您将路由定义为[Route("{tier:int}/monitor")] ,则可能没有歧义。 Alternatively, you can add a regex to the routes, to make them exclusive, something like {tier:regex(^(?!reactive))?} would let you resolve this. 或者,你可以在路由中添加一个正则表达式,使它们成为独占的,像{tier:regex(^(?!reactive))?}可以让你解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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