【问题标题】:ASP.NET Web API Routing Query ParametersASP.NET Web API 路由查询参数
【发布时间】:2013-11-11 23:23:55
【问题描述】:

我有一个 StudentsController,我目前有以下工作:

http://mycompany.com/api/v1/students   <-- returns list of students
http://mycompany.com/api/v1/students/5 <-- returns student with Id = 5

我有一个要求让 2013 级的所有学生返校,但下面的当然行不通:

http://mycompany.com/api/v1/students/2013 <-- won't work, because it would look for the student with Id = 2013

我可以这样做:

http://mycompany.com/api/v1/students?gradclass=2013

但我想知道是否有一种方法可以在没有查询字符串的情况下进行,例如:

http://mycompany.com/api/v1/students/gradclasses/2013

上面说的有点道理,但这说不通:

http://mycompany.com/api/v1/students/gradclasses <-- this sort of makes no sense

另外,一旦我们弄清楚了使用路由设置正确解决方案的方法是什么?

这值得吗?最佳做法是什么?我正在努力寻找有关 REST 和 GET 查询参数的最佳实践。

【问题讨论】:

  • 学生和班级应该是不同的资源...所以获取班级所有学生的 uri 应该像 /class/{year}/students 并且可能指向班级控制器...如果您不喜欢有一个不同的控制器,您可以在学生控制器中执行操作(获取一个班级的所有学生)并用属性路由装饰它......
  • 这是有道理的。但是,如果我想向所有有工作机会的学生展示呢?然后是另一个我想展示没有工作机会的学生的案例?另外,直接在 /class 上的 GET 会是什么样子?

标签: rest asp.net-web-api


【解决方案1】:

我会将“2013 届学生”视为一种观点。然后将 api 编写为 /type/view/params。 所以: http://mycompany.com/api/v1/students/byclass/2013
http://mycompany.com/api/v1/students/withJobOffer
http://mycompany.com/api/v1/students/repeaters/2012

确实视图可以重叠。那更复杂。然后你必须处理查询字符串: http://mycompany.com/api/v1/students?class=2013&withJobOffer=true&repeaters=2012

【讨论】:

    【解决方案2】:

    由于 REST 是关于思考可以浏览的资源,即使事先不知道结构,我也会添加你的工作示例,即通过将等级课程视为另一种类型的资源来获取所有学生和单个学生,像这样:

    http://mycompany.com/api/v1/gradclasses/ => Return all grad classes
    http://mycompany.com/api/v1/gradclasses/2013/ => Return a grad class of 2013 with it's info
    http://mycompany.com/api/v1/gradclasses/2013/students/ => Return the students of grad class 2013
    

    这样,您将拥有良好的关系和易于探索的内容。

    更进一步,如果您想抽象出学生拥有全球唯一 ID 以增加持久性无知这一事实,您可以仅按以下方式实现学生的获取:

    http://mycompany.com/api/v1/gradclasses/2013/students/5 => Return the student 5 of grad class 2013
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 2012-09-05
      • 2015-10-09
      • 2013-05-14
      相关资源
      最近更新 更多