[英]Routing multiple GET methods from same controller - Web Api
我目前正在使用的Web Api有问题。
我有一个带有两个Get方法的控制器。 一个返回对象列表的对象。 另一个返回相同对象的列表,但根据传入的某些参数进行过滤。如下所示:
public IList<MyObject> Get(int id)
{
//Code here looks up data, for that Id
}
public IList<MyObject> Get(int id, string filterData1, string filterData2)
{
//code here looks up the same data, but filters it based on 'filterData1' and 'filterData2'
}
我无法为此使用路线。 特别是因为Api帮助页面似乎多次显示相同的url。
我的路线如下:
config.Routes.MapHttpRoute(
name: "FilterRoute",
routeTemplate: "api/Mycontroller/{Id}/{filterData1}/{filterData2}",
defaults: new { controller = "Mycontroller" }
);
config.Routes.MapHttpRoute(
name: "normalRoute",
routeTemplate: "api/Mycontroller/{Id}",
defaults: new { controller = "Mycontroller" }
);
有人知道吗
另外,是否可以将我的过滤方法更改为类似
public IList<MyObject> Get(int Id, FilterDataObject filterData)
{
//code here
}
还是不能在Get上传递复杂的对象?
尝试查看属性路由 nuget包。 这使您可以为控制器中的每个方法定义自定义URL。
关于第二个问题,由于没有请求主体可保存值,因此无法通过get请求发送复杂的对象,您将需要使用POST方法来执行此操作。
假设您有以下路线:
routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{controller}/{id}/{p1}/{p2}",
defaults: new { id = RouteParameter.Optional, p1 = RouteParameter.Optional, p2 = RouteParameter.Optional });
GET api/controller?p1=100
映射到public HttpResponseMessage Get(int p1) {}
GET api/controller/1?p1=100
映射到public HttpResponseMessage Get(int id, int p1) {}
GET api/controller/1
映射到public HttpResponseMessage Get(int id) {}
等等...
GET和复杂模型绑定:根据定义,复杂模型应位于请求正文中(独立于动词)(URL包含可能破坏复杂模型的长度限制)。 您可以通过以下方法强制WebApi在URL中查找复杂模型:
routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{controller}/{customer}");
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
public HttpResponseMessage Get([FromUri] Customer customer) {};
GET api/customers?id=1&name=Some+name
请注意:大多数情况下,使用复杂类型的GET(如我的示例)毫无意义。 为什么要通过ID和名称获得客户? 根据定义,复杂类型需要POST(CREATE)或PUT(UPDATE)。
要使用子文件夹结构进行调用,请尝试:
routes.MapHttpRoute(
"MyRoute",
"api/{controller}/{id}/{p1}/{p2}",
new { id = UrlParameter.Optional, p1 = UrlParameter.Optional, p2 = UrlParameter.Optional, Action = "Get"});
GET /api/controller/2134324/123213/31232312
public HttpResponseMessage Get(int id, int p1, int p2) {};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.