asp.net-mvc - 为什么这两个 API 方法会产生冲突

标签 asp.net-mvc asp.net-mvc-4 asp.net-web-api

我们正在开发一个 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 会抛出错误不同:

  1. Post 方法中删除 Get AcceptVerbs 属性
  2. 更改 Get 方法的签名以接受整数形式的枚举

最佳答案

这是 ASP.NET Web API 中的一个已知行为/问题/错误。

简而言之,当尝试将传入的 HTTP 请求与 Controller 内的相关操作进行匹配时,操作选择器 (IHttpActionSelector) 不会考虑 Enums

原因是默认情况下仅从 RouteData 中选取原始类型(即 intstring 等)来查找匹配的操作。 Enum 不是其中之一,因此它被忽略,因此,即使从编译器的角度来看您的操作具有不同的签名,但在操作选择器的眼中它们是相同的。

您可以在此处跟踪潜在修复的进度 - http://aspnetwebstack.codeplex.com/workitem/312

目前,正如您自己所说,最好的解决方法是将 enum 作为 intstring 传递(并强制转换为 枚举)。

关于asp.net-mvc - 为什么这两个 API 方法会产生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14591447/

相关文章:

c# - Web API 创建 API key

html - 如何覆盖 TextBoxFor 字段的 CSS?

jquery - 使用 Jquery 限制/计数 CKEditor 中的字符

c# - 在 C# 属性中替换字符串

c# - 不能在 LINQ 中隐式转换类型

javascript - 如何在 JavaScript 中捕获错误的 URL?

c# - C# 中对象(带数组)的 API

c# - MVC 4 客户端验证不起作用

c# - 如何防止 MVC Controller 中的并发访问?

logging - 应该如何处理内部 web api 错误?