one*_*mer 9 rest asp.net-mvc asp.net-mvc-routing asp.net-mvc-3
我想为我的MVC3应用程序构建一个RESTful Json Api.我需要帮助处理多个Http Verbs来操作单个对象实例.
我读过/研究/尝试过的内容
MVC属性(HttpGet,HttpPost等)允许我让一个控制器具有共享相同名称的多个动作,但它们仍然必须具有不同的方法签名.
在 MVC启动之前路由模块中发生路由约束并且会导致我有4个显式路由,并且仍然需要单独命名的控制器操作.
构建自定义Http Verb属性可用于获取用于访问操作的动词,然后在调用操作时将其作为参数传递 - 然后代码将处理切换案例.这种方法的问题是某些方法需要授权,应该在动作过滤器级别处理,而不是在动作本身内部.
http://iwantmymvc.com/rest-service-mvc3
要求/目标
单个实例对象的一个路由签名,MVC预计将处理四个主要的Http动词:GET,POST,PUT,DELETE.
context.MapRoute("Api-SingleItem", "items/{id}",
new { controller = "Items", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)当URI未传递Id参数时,操作必须处理POST和PUT.
public JsonResult Index(Item item) { return new JsonResult(); }
Run Code Online (Sandbox Code Playgroud)当Id参数传递给URI时,单个操作应该处理GET和DELETE.
public JsonResult Index(int id) { return new JsonResult(); }
Run Code Online (Sandbox Code Playgroud)题
我怎样才能有多个动作(共享相同的名称和方法签名),每个动作都响应一个唯一的http动词.期望的例子:
[HttpGet]
public JsonResult Index(int id) { /* _repo.GetItem(id); */}
[HttpDelete]
public JsonResult Index(int id) { /* _repo.DeleteItem(id); */ }
[HttpPost]
public JsonResult Index(Item item) { /* _repo.addItem(id); */}
[HttpPut]
public JsonResult Index(Item item) { /* _repo.updateItem(id); */ }
Run Code Online (Sandbox Code Playgroud)
Luc*_*ero 10
对于RESTful调用,该操作没有意义,因为您只想通过HTTP方法区分.因此,诀窍是使用静态操作名称,以便控制器上的不同方法仅在它们接受的HTTP方法中有所不同.
虽然MVC框架提供了指定动作名称的解决方案,但它可以更简洁和自我解释.我们解决了这个问题:
特殊属性用于指定RESTful方法(这与特殊操作名称匹配):
public sealed class RestfulActionAttribute: ActionNameSelectorAttribute {
internal const string RestfulActionName = "<<REST>>";
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) {
return actionName == RestfulActionName;
}
}
Run Code Online (Sandbox Code Playgroud)
控制器将它与HTTP方法属性结合使用:
public class MyServiceController: Controller {
[HttpPost]
[RestfulAction]
public ActionResult Create(MyEntity entity) {
return Json(...);
}
[HttpDelete]
[RestfulAction]
public ActionResult Delete(Guid id) {
return Json(...);
}
[HttpGet]
[RestfulAction]
public ActionResult List() {
return Json(...);
}
[HttpPut]
[RestfulAction]
public ActionResult Update(MyEntity entity) {
return Json(...);
}
}
Run Code Online (Sandbox Code Playgroud)
为了成功绑定这些控制器,我们使用自定义路由和来自beforementionned属性的静态操作名称(同时也允许自定义URL):
routes.MapRoute(controllerName, pathPrefix+controllerName+"/{id}", new {
controller = controllerName,
action = RestfulActionAttribute.RestfulActionName,
id = UrlParameter.Optional
});
Run Code Online (Sandbox Code Playgroud)
请注意,据我所知,这种方法可以轻松满足您的所有要求; 您可以在一个方法上具有多个[HttpXxx]属性,以使一个方法接受多个HTTP方法.与一些智能(呃)ModelBinder搭配使用非常强大.
| 归档时间: |
|
| 查看次数: |
6347 次 |
| 最近记录: |