当我尝试有2个“Get”方法时,我一直得到这个错误
发现了多个与请求:webapi匹配的操作
我一直在看其他类似的问题,但我不明白。
我有2个不同的名字,并使用“HttpGet”属性
[HttpGet]
public HttpResponseMessage Summary(MyVm vm)
{
return null;
}
[HttpGet]
public HttpResponseMessage FullDetails()
{
return null;
}
当我尝试有2个“Get”方法时,我一直得到这个错误
发现了多个与请求:webapi匹配的操作
我一直在看其他类似的问题,但我不明白。
我有2个不同的名字,并使用“HttpGet”属性
[HttpGet]
public HttpResponseMessage Summary(MyVm vm)
{
return null;
}
[HttpGet]
public HttpResponseMessage FullDetails()
{
return null;
}
当前回答
从Web API 2开始更新。
在WebApiConfig.cs文件中使用这个API配置:
public static void Register(HttpConfiguration config)
{
//// Web API routes
config.MapHttpAttributeRoutes(); //Don't miss this
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
}
你可以像这样路由我们的控制器:
[Route("api/ControllerName/Summary")]
[HttpGet]
public HttpResponseMessage Summary(MyVm vm)
{
return null;
}
[Route("api/ControllerName/FullDetails")]
[HttpGet]
public HttpResponseMessage FullDetails()
{
return null;
}
其中ControllerName是控制器的名称(没有“controller”)。这将允许您使用上面详细介绍的路由获取每个操作。
欲进一步阅读:http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
其他回答
我发现,当我有两个Get方法时,一个无参数,一个以复杂类型作为参数,我得到了相同的错误。我通过添加一个名为Id的int类型的虚拟参数作为我的第一个参数来解决这个问题,后面跟着我的复杂类型参数。然后,我将复杂类型参数添加到路由模板中。下面的方法对我很有效。
第一个获得:
public IEnumerable<SearchItem> Get()
{
...
}
第二个获得:
public IEnumerable<SearchItem> Get(int id, [FromUri] List<string> layers)
{
...
}
WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{layers}",
defaults: new { id = RouteParameter.Optional, layers RouteParameter.Optional }
);
在Web API中(默认情况下),方法的选择是基于HTTP方法和路由值的组合。
MyVm看起来像一个复杂的对象,由格式化器从对象体中读取,因此在路由数据方面有两个相同的方法(因为它们都没有来自路由的任何参数)——这使得分派器(IHttpActionSelector)不可能匹配适当的方法。
您需要通过查询字符串或路由参数来区分它们以解决歧义。
我在尝试用额外的操作来增强我的WebAPI控制器时偶然发现了这个问题。
假设你会
public IEnumerable<string> Get()
{
return this.Repository.GetAll();
}
[HttpGet]
public void ReSeed()
{
// Your custom action here
}
现在有两个方法可以满足/api/controller的请求,这个请求会触发TS所描述的问题。
我不想为我的附加动作添加“虚拟”参数,所以我查看了默认动作,并提出:
[ActionName("builtin")]
public IEnumerable<string> Get()
{
return this.Repository.GetAll();
}
对于第一种方法,结合“dual”路由绑定:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { action = "builtin", id = RouteParameter.Optional },
constraints: new { id = @"\d+" });
config.Routes.MapHttpRoute(
name: "CustomActionApi",
routeTemplate: "api/{controller}/{action}");
请注意,即使在第一个路由模板中没有“action”参数,显然你仍然可以配置一个默认动作,允许我们分离“正常”WebAPI调用的路由和对额外动作的调用。
就我而言,一切都是对的
1) Web Config配置正确 2)路由前缀和路由属性正确
我还是得到了错误。在我的案例中,“Route”属性(通过按F12)指向System.Web.MVc,而不是System.Web.Http,这导致了问题。
确保你没有装饰你的控制器方法默认的GET|PUT|POST|DELETE动作与[HttpPost/ PUT / GET / DELETE]属性。我已经将此属性添加到我的香草后控制器动作,它导致404。
希望这能帮助到一些人,因为它可能会非常令人沮丧,并导致进展停滞。