微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – MVC3 REST路由和Http动词

作为我的 previous question一个结果,我发现了在MVC3中处理REST路由的两种方式.

这是一个后续问题,我正在尝试学习这两种方法间的事实差异/微妙之处.如果可能,我正在寻求权威的答案.

方法1:单路由,操作名称Http控制器动作的动态属性

>使用指定的动作参数在Global.asax中注册一条路线.

public override void Registerarea(AreaRegistrationContext context)
{
    // actions should handle: GET,POST,PUT,DELETE
    context.MapRoute("Api-SinglePost","api/posts/{id}",new { controller = "Posts",action = "SinglePost" });
}

>将ActionName和HttpVerb属性应用于控制器操作

[HttpGet]
[ActionName("SinglePost")]
public JsonResult Get(string id)
{
    return Json(_service.Get(id));
}
[HttpDelete]
[ActionName("SinglePost")]
public JsonResult Delete(string id)
{
    return Json(_service.Delete(id));
}
[HttpPost]
[ActionName("SinglePost")]
public JsonResult Create(Post post)
{
    return Json(_service.Save(post));
}
[HttpPut]
[ActionName("SinglePost")]
public JsonResult Update(Post post)
{
    return Json(_service.Update(post););
}

方法2:唯一路由动词约束,控制器动作具有Http动词属性

>使用HttpMethodContraint在Global.asax中注册唯一的路由

var postsUrl = "api/posts";

routes.MapRoute("posts-get",postsUrl + "/{id}",action = "Get",new { httpMethod = new HttpMethodConstraint("GET") });

routes.MapRoute("posts-create",postsUrl,action = "Create",new { httpMethod = new HttpMethodConstraint("POST") });

routes.MapRoute("posts-update",action = "Update",new { httpMethod = new HttpMethodConstraint("PUT") });

routes.MapRoute("posts-delete",action = "Delete",new { httpMethod = new HttpMethodConstraint("DELETE") });

>在控制器操作上仅使用Http动词属性

[HttpGet]
public JsonResult Get(string id)
{
    return Json(_service.Get(id));
}
[HttpDelete]
public JsonResult Delete(string id)
{
    return Json(_service.Delete(id));
}
[HttpPost]
public JsonResult Create(Post post)
{
    return Json(_service.Save(post));
}
[HttpPut]
public JsonResult Update(Post post)
{
    return Json(_service.Update(post););
}

这两种方法都让我有独一无二的命名控制器操作方法,并允许与动词绑定的RESTful路由…但是限制路由与使用代理操作名称有什么不同?

解决方法

你不会得到一个权威的答案,这里是我的2美分:

我更喜欢方法2,因为那里你有一个地方的所有路由.您可以将路由封装成一个方法,例如MapResourceRoutes(字符串控制器,字符串uri),并在整个API中使用了多个时间.

另外,方法2给出了可以用于链接和反向路由的清晰命名的路由.

原文地址:https://www.jb51.cc/csharp/93884.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐