REST路由&动词 - 处理没有参数的路线

时间:2012-05-10 23:55:31

标签: asp.net-mvc-3 api http rest routes

背景

我为一个简单的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)始终存在,即使在POSTPUT请求上也是如此。

使用上面显示的这个新API,POSTPUT操作不会触发顶部路由(例如,无{id}值),当它们触发第二条路径时,由于动词,没有办法处理它们。

问题

维护这个REST-ful URL架构和动词处理的最佳方法是什么,并确保我触发POST和PUT操作?

0 个答案:

没有答案