从同一控制器路由多个 GET 方法 - 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 上传递复杂对象吗?

假设您有以下路线:

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(创建)或 PUT(更新)。

要使用子文件夹结构进行调用,请尝试:

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) {};

尝试查看属性路由 nuget 包。这允许您为控制器中的每个方法定义自定义 URL。

关于第二个问题,您不能通过 get 请求发送复杂对象,因为没有请求正文来保存值,您需要使用 POST 方法来执行此操作。

最新更新