如何处理WebAPI上的路由冲突 - 字符串ID与action + id

Jim*_*Jim 1 .net c# asp.net-web-api attributerouting

我正在使用.NET 4上的Web API(nuget上的WebAPI版本4.0.30506)托管REST API.为了允许更精细的属性路由,我还在我的解决方案中包含了attributerouting.net.

我有2个冲突的属性路由.冲突的原因是我们在一次调用中通过字符串标识符查询,并在另一次调用中通过字符串操作+数字标识符进行查询.HTTP响应中抛出的消息读取Multiple actions were found that match the request.以下是演示这两者的示例查询:

1) http://example/api/libraries/?libraryId=some_library (some_library is a string identifier)

2) http://example/api/libraries/bookStatus/1 (1 is the library database ID) 
Run Code Online (Sandbox Code Playgroud)

我一直在努力通过不同的方式来完成这项工作.我当前的控制器签名如下所示:

[GET("api/libraries/?libraryId={libraryId}", Precedence = 2)]
[System.Web.Http.HttpGet]
public Library QueryLibraryByLibraryId(string libraryId){}

[GET("api/libraries/bookStatus/{libraryId:long}", Precedence = 1)]
[System.Web.Http.HttpGet]
public Dictionary<string, Dictionary<string, string>> QueryBookStatus(long libraryId){}
Run Code Online (Sandbox Code Playgroud)

我可以看到为什么路由可能会混淆:它如何知道字符串标识符"bookStatus/1"无效是一个很好的问题.但是,我认为这应该更容易定义一些约束.

如何在保持此类签名结构的同时解决这些冲突?

Fen*_*hao 6

问题是默认的WebAPI路由约定在属性路由之前匹配.

您应该将属性路由设置为默认路由,这意味着在WebApiConfig.cs中,您需要调用

config.Routes.MapHttpAttributeRoutes

首先在打电话给别人之前

config.Routes.MapHttpRoute.

还有一个可选的提示,您不需要在第一个方法的查询部分中指定libraryId.

它可以自动完成.

        [GET("api/libraries", Precedence = 2)]
        [System.Web.Http.HttpGet]
        public Library QueryLibraryByLibraryId(string libraryId) { }

        [GET("api/libraries/bookStatus/{libraryId:long}", Precedence = 1)]
        [System.Web.Http.HttpGet]
        public Dictionary<string, Dictionary<string, string>> QueryBookStatus(long libraryId) { }
Run Code Online (Sandbox Code Playgroud)