加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 06:23:03 所属栏目:asp.Net 来源:网络整理
导读:我们正在开发一个MVC4 API应用程序,遇到了一个我们没有解释的奇怪问题. API控制器有两种方法: [AllowAnonymous] [AcceptVerbs("Post","Get")] public ArtifactContent Post(string userName,string password,string id) ... 和 [AllowAnonymous] [AcceptVer
我们正在开发一个MVC4 API应用程序,遇到了一个我们没有解释的奇怪问题.

API控制器有两种方法:

[AllowAnonymous]
    [AcceptVerbs("Post","Get")]
    public ArtifactContent Post(string userName,string password,string id) ...

[AllowAnonymous]
    [AcceptVerbs("Get")]
    public HttpResponseMessage Get(string userName,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.ArtifactContentControllerrnSystem.Net.Http.HttpResponseMessage
Get(System.String,ArtifactContentTypes) on type
[XXX].API.ArtifactContentController”,”ExceptionType”:”System.InvalidOperationException”,”StackTrace”:”
at
System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext
controllerContext)rn at
System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext
controllerContext)rn at
System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext
controllerContext,CancellationToken cancellationToken)rn at
System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage
request,CancellationToken cancellationToken)rn at
System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage
request,CancellationToken cancellationToken)”}

我们可以通过进行这两个更改中的一个来解决错误,但我真的想知道为什么.NET在两个签名明显不同时抛出错误:

>从Post方法中删除Get AcceptVerbs属性
>更改Get方法的签名以将Enum接受为整数

解决方法

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

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

原因是默认情况下,只从RouteData中选择基本类型(即int,string等)以查找匹配的操作.枚举不是其中之一,所以它被忽略了,因此,即使你的动作与编译器的角度有不同的签名,在动作选择器的眼中它们是相同的.

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

就目前而言,正如你自己所说,最好的解决方法是将枚举作为int或string传递(并转换为枚举).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读