WebAPI 2的RoutePrefix Order替代 [英] RoutePrefix Order alternative for WebAPI 2

查看:118
本文介绍了WebAPI 2的RoutePrefix Order替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WebAPI中,您可以在 RouteAttribute 中指定 Order ,以确定路由的匹配顺序.例如,以下内容将匹配/other 匹配/blah GetByName

In WebAPI you can specify an Order in RouteAttribute to determine which order the routes are matched in. For example the below will match /other to GetOther before matching /blah to GetByName

[HttpGet, Route("{name}", Order = 1)]
public string GetByName(string name) { ... }

[HttpGet, Route("other")]
public string GetOther() { ... }

如果使用 RoutePrefix (没有 Order 属性),我该怎么做?如果这样做,它将看起来像这样:

How would I do the same but with RoutePrefix (which doesn't have an Order property)? If it did it would looks something like this:

[RoutePrefix("foo", Order = 1)]
public class FooController : ApiController { ... }

[RoutePrefix("foo/bar")]
public class FooBarController : ApiController { ... }

执行上述操作(不带假想的 Order 属性)会在调用/foo/bar 时引发以下消息:

Doing the above (without the imaginary Order property) throws the following message when calling /foo/bar:

发现与URL匹配的多种控制器类型

Multiple controller types were found that match the URL

是否存在解决此问题的功能(最好是带有属性)?

Is there existing functionality for getting around this (preferably with attributes)?

推荐答案

我不相信 Microsoft的属性路由支持按控制器排序路由.

I don't believe Microsoft's attribute routing has support for ordering routes by controller.

在动作的 RouteAttribute 上指定 Order 属性时,您仅在控制器内指定顺序.

When you specify an Order property on an action's RouteAttribute, you are specifying the order within the controller only.

AFAIK,属性路由算法将按字母顺序扫描所有控制器.然后在每个控制器内,将使用任何 RouteAttribute Order 属性来确定该控制器内动作路线的顺序.

AFAIK, the attribute routing algorithm will scan all of the controllers alphabetically. Then within each controller, is will use the Order property of any RouteAttributes to decide the order of action routes within that controller.

这意味着,如果路由冲突分散在不同的控制器上,则应该重新考虑设计,或者确保具有更特定路由模式的控制器在按字母顺序命名之前,将具有更通用路由模式的控制器命名为字母.否则,您可能会遇到歧义路线/找到具有匹配路线的多个操作"例外.

This means if you have route collisions spread across different controllers, you should either rethink the design or make sure the controllers with the more specific route patterns are named alphabetically before the controllers with the more general route patterns. Otherwise, you may run into that "ambiguous route / multiple actions with matching routes found" exception.

更新:上面的答案是针对Microsoft的AttributeRouting实现的,它是基于另一个MVC5之前的流行的开源项目.在该库中,您可以按控制器排序属性路由,尽管我认为该属性是 SiteOrder 或类似的东西.

Update: The answer above is for Microsoft's AttributeRouting implementation, which was based on another very popular open source project that came before MVC5. In that library, you could order attribute routes by controller, though I think the property was SiteOrder or something like that.

这篇关于WebAPI 2的RoutePrefix Order替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆