RESTful -按所有者ID获取资源列表
本文关键字:获取 资源 列表 ID 所有者 RESTful | 更新日期: 2023-09-27 18:11:07
我需要获得属于特定部门的部门列表。根据REST基础,/dept/1
URL应该用于通过ID获取特定的部门,因此不能在这里使用。
然后我有以下选项:
/dept/division/1
看起来不像真正的REST。此外,我不知道如何在WebApi操作方面实现它。
/dept?divId=1
看起来更RESTful。它将需要创建Get(int divId)
操作,但也有Get(int id)
操作,用于检索单个部门并具有相同的签名。
/dept (with divId=1 in the body)
它是否足够RESTful ?但它会有与#2相同的签名问题…
请告诉我哪条路更好。谢谢你!
我会怎么做
/divisions/1/depts
/divisions/1
获取ID为1的单个部门,/depts
获取属于该特定部门的所有部门
这当然可以扩展到
/divisions/1/depts/234
获取ID为234的部门,属于第1事业部。
不需要这样通过body传递信息。
我使用复数作为资源名,因为我习惯这样做,如果你想用division
和dept
来代替,这将是很好的
public class DivisionsController : ApiController
{
[Route("/Divisions/{id}")]
[HttpGet]
public Division GetDivision(int id)
{
return // your code here
}
[Route("/Divisions/{id}/Dept")]
[HttpGet]
public IEnumerable<Department> GetDepartments(int id)
{
return // your code here
}
[Route("/Divisions/{id}/Dept/{deptId}")]
[HttpGet]
public Department GetDepartment(int id, int deptId)
{
return // your code here
}
}
或者用更简洁的方式
[RoutePrefix("/divisions/{id}")]
public class DivisionsController : ApiController
{
[Route]
[HttpGet]
public Division GetDivision(int id)
{
return // your code here
}
[Route("Dept")]
[HttpGet]
public IEnumerable<Department> GetDepartments(int id)
{
return // your code here
}
[Route("Dept/{deptId}")]
[HttpGet]
public Department GetDepartment(int id, int deptId)
{
return // your code here
}
}