![](/img/trans.png)
[英]All methods act as a HTTP verb (Get, Put, Post And Delete) in ASP.NET WEB API controller
[英]In a RESTful application, how do we differentiate between an “action” and an HTTP verb (GET, POST, PUT, DELETE)?
在RESTful应用程序中,我们如何区分“动作”和HTTP动词( GET
, POST
, PUT
, DELETE
)?
例如,据我所知,对资源/products
的GET
请求应返回所有产品的列表。 对/products
POST
请求应该创建一个新产品。 那么,用户如何请求用于创建产品的原始表单? 我的初始响应是对同一URI的GET
请求,但如上所述,它应该返回所有产品的列表 - 而不是用于创建产品的空白表单。
在我研究的大多数框架中,通过使URI的“动作”部分来解决这个问题。 例如,对/products/create
的POST
请求将创建新产品,而对/products/create
的GET
请求将为创建产品提供空白表单。 获取所有产品的列表将是对/products
或/products/get
, /products/read
等的GET
请求,具体取决于相关框架。 这种方法解决了上面的歧义,但它与我读到的有关传统REST设计的内容相冲突。
恕我直言,最好的选择是使请求方法成为控制器操作的一部分。
假设您正在访问http://who.cares/product/42
或http://who.cares/product/42/specification
。 对webserver的此查询将转换为Product
controller。 应该通过组合请求方法和命令来创建操作名称:
DELETE "http://who.cares/product/42"
controller: "Product",
action: "deleteProduct()"
GET "http://who.cares/product/42/details"
controller: "Product",
action: "getDetails()"
POST "http://who.cares/product/42/review"
controller: "Product",
action: "postReview()"
GET "http://who.cares/products/
controller: "Products",
action: "getProducts()"
POST "http://who.cares/products/
controller: "Products",
action: "postProducts()"
这里是Rails的例子
REST request path | action name | Description
---------------------|-------------------|-------------
GET /profile/new | new | Render a form for creating the profile
POST /profile | create | Create a the profile from the received data
GET /profile | show | Render a the profile
GET /profile/edit | edit | Render a form for editing the profile
PUT /profile | update | Update the profile based on the received data
DELETE /profile | destroy | Destroy the profile
我没有看到任何冲突,想法是网址是人类可读的,你可以引入新的URI来显示同一资源的不同表示。 (如个人资料/ 1 /编辑和个人资料/ 1)/个人资料/新 - 空的个人资料地址(如个人资料/ 1,个人资料/ 2 ..等方式)但如果你想要你可以建议个人资料/ 1 / edit是某种不同的 - profile / 1 / resource的嵌套资源,但我喜欢它只是profile / 1 / resource =的其他表示
当你使用多个资源或使用一个例子时,使用复数和单数URI也是个好主意
/profile/1.html - gives you 1 resource
/profiles.html - gives you list of profiles
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.