我为一个简单的Blog应用程序编写了一个类似REST的API服务控制器。我使用两条路径来处理基本的CRUD:
// Actions should handle: GET, POST, PUT, DELETE
routes.MapRoute("Api-SingleThing", "thing/{id}",
new { controller = "ThingService", action = "SingleThing" });
// Action should handle: GET
routes.MapRoute("Api-AllThings", "things",
new { controller = "ThingService", action = "AllThings" });
匹配的控制器代码如下:
[HttpGet]
public ActionResult AllThings() {}
[HttpGet]
[ActionName("SingleThing")]
public ActionResult Get(string id) {}
[HttpPost]
[ActionName("SingleThing")]
public JsonResult Create(Thing thing) {}
[HttpPut]
[ActionName("SingleThing")]
public ActionResult Update(Thing thing) {}
[HttpDelete]
[ActionName("SingleThing")]
public ActionResult Delete(int id) {}
[ActionName()]
属性用于避免路由约束,因此触发时的路由始终会调用控制器上的“SingleThing”操作 - 无论HTTP谓词如何。这使得共享名称的控制器操作方法可以根据[HttpVerb]
属性决定谁处理请求。
在我的博客应用中,这就像魅力,但只是因为{id}
路由参数(又称slug)始终存在,即使在POST
和PUT
请求上也是如此。
使用上面显示的这个新API,POST
和PUT
操作不会触发顶部路由(例如,无{id}
值),当它们触发第二条路径时,由于动词,没有办法处理它们。
维护这个REST-ful URL架构和动词处理的最佳方法是什么,并确保我触发POST和PUT操作?