当我尝试有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;
}
当前回答
这个解决方案对我很有效。
请将Route2放在WebApiConfig的前面。在每个方法之前添加HttpGet和HttpPost,并在url中包含控制器名和方法名。
WebApiConfig = >
config.Routes.MapHttpRoute(
name: "MapByAction",
routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
控制器= >
public class ValuesController : ApiController
{
[HttpPost]
public string GetCustomer([FromBody] RequestModel req)
{
return "Customer";
}
[HttpPost]
public string GetCustomerList([FromBody] RequestModel req)
{
return "Customer List";
}
}
Url = >
http://localhost:7050/api/Values/GetCustomer
http://localhost:7050/api/Values/GetCustomerList
其他回答
在Web API中(默认情况下),方法的选择是基于HTTP方法和路由值的组合。
MyVm看起来像一个复杂的对象,由格式化器从对象体中读取,因此在路由数据方面有两个相同的方法(因为它们都没有来自路由的任何参数)——这使得分派器(IHttpActionSelector)不可能匹配适当的方法。
您需要通过查询字符串或路由参数来区分它们以解决歧义。
我知道这是一个老问题,但有时,当你使用AngularJS中的服务资源连接到WebAPI时,确保你使用了正确的路由,否则会发生这个错误。
有可能你的webmethods被解析为相同的url。请浏览以下连结:-
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
所以,你可能需要将你的methodname添加到路由表中。
这个解决方案对我很有效。
请将Route2放在WebApiConfig的前面。在每个方法之前添加HttpGet和HttpPost,并在url中包含控制器名和方法名。
WebApiConfig = >
config.Routes.MapHttpRoute(
name: "MapByAction",
routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
控制器= >
public class ValuesController : ApiController
{
[HttpPost]
public string GetCustomer([FromBody] RequestModel req)
{
return "Customer";
}
[HttpPost]
public string GetCustomerList([FromBody] RequestModel req)
{
return "Customer List";
}
}
Url = >
http://localhost:7050/api/Values/GetCustomer
http://localhost:7050/api/Values/GetCustomerList
你可以添加[Route("api/[controller]/[action]")]到你的控制器类中。
[Route("api/[controller]/[action]")]
[ApiController]
public class MySuperController : ControllerBase
{
...
}