我们正在开发一个 MVC4 API 应用程序,并遇到了一个我们无法解释的奇怪问题。
API Controller 有两种方法:
[AllowAnonymous]
[AcceptVerbs("Post", "Get")]
public ArtifactContent Post(string userName, string password, string id) ...
和
[AllowAnonymous]
[AcceptVerbs("Get")]
public HttpResponseMessage Get(string userName, string password, string id, EnumType contentType) ...
尽管这两个方法显然具有不同的方法签名,但我们收到以下错误消息:
{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: [XXX].Models.ArtifactContent Post(System.String, System.String, System.String) on type [XXX].API.ArtifactContentController\r\nSystem.Net.Http.HttpResponseMessage Get(System.String, System.String, System.String, ArtifactContentTypes) on type [XXX].API.ArtifactContentController","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)"}
我们可以通过进行这两项更改之一来解决该错误,但我真的想知道为什么当两个签名明显时.NET 会抛出错误不同:
- 从
Post
方法中删除Get
AcceptVerbs
属性 - 更改
Get
方法的签名以接受整数形式的枚举
最佳答案
这是 ASP.NET Web API 中的一个已知行为/问题/错误。
简而言之,当尝试将传入的 HTTP 请求与 Controller 内的相关操作进行匹配时,操作选择器 (IHttpActionSelector
) 不会考虑 Enums
。
原因是默认情况下仅从 RouteData
中选取原始类型(即 int
、string
等)来查找匹配的操作。 Enum
不是其中之一,因此它被忽略,因此,即使从编译器的角度来看您的操作具有不同的签名,但在操作选择器的眼中它们是相同的。
您可以在此处跟踪潜在修复的进度 - http://aspnetwebstack.codeplex.com/workitem/312
目前,正如您自己所说,最好的解决方法是将 enum
作为 int
或 string
传递(并强制转换为 枚举
)。
关于asp.net-mvc - 为什么这两个 API 方法会产生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14591447/