REST WebAPI - 操作和子控制器怎么样?

时间:2013-11-04 16:10:15

标签: c# rest asp.net-web-api

我们在这里有一个RESTful WebAPI服务,我一直想知道如何构建我的代码和路由以应对以下内容:

http://myapi/customer/1/files

http://myapi/customer/1/files/3

所以我基本上有一个管理客户信息的客户控制器,一个管理文件信息的文件控制器,如果我想要客户1的所有文件,我可能会做第一个请求。

我真的不想在客户的上下文中管理它,所以当我对文件的GET关注文件的ID时,我将不得不重载它并做

http://myapi/files/?customer=1&files=all

它似乎比第一种解决方案更不干净?

目前我有以下内容:

config.Routes.MapHttpRoute(name: SubController, routeTemplate: "{entity}/{entityid}/{controller}/", defaults: null);
config.Routes.MapHttpRoute(name: SubControllerAndId, routeTemplate: "{entity}/{entityid}/{controller}/{id}", defaults: null);

发送FilesController时会解析为http://myapi/customer/1/files

[HttpGet]
    public HttpResponseMessage Get(string entity, string entityid, int id)
    {
        var item = "Hello " + entity + " " + entityid + " "  + id;
        return Request.CreateResponse(HttpStatusCode.OK, item);
    }

[HttpGet]
    public HttpResponseMessage Get(string entity, string entityid)
    {
        var item = "Hello " + entity + " " + entityid;
        return Request.CreateResponse(HttpStatusCode.OK, item);
    }

这可以在customer作为实体传递,1作为实体ID传递,但它不是最好的解决方案,有没有更好的方法来做到这一点,这是错误的?

1 个答案:

答案 0 :(得分:1)

Kiran是对的。 Nuget属性路由似乎正是你在寻找什么。

Heres的样子如下:

public class CustomerController : ApiController
{
    [HttpGet]
    [GET("api/customer/{id}/files")]
    public HttpResponseMessage Get(int id)
    {
    //code
    }

    [HttpGet]
    [GET("api/customer/{id}/files/{fileId}")]
    public HttpResponseMessage Get(int id, int fileId)
    {
    //code
    }
}
相关问题