使用不同Http方法的RESTful控制器,但相同的参数

Dus*_*sda 4 rest asp.net-mvc crud

假设我有一个Controller来处理'Home'的CRUD场景.Get会看起来像这样:

    [HttpGet]
    public ActionResult Index(int? homeId)
    {
        Home home = homeRepo.GetHome(homeId.Value);

        return Json(home, JsonRequestBehavior.AllowGet);
    }
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.然后我添加了一个用于添加新帖子的帖子操作.

    [HttpPost]
    public ActionResult Index(Home home)
    {
        //add the new home to the db

        return Json(new { success = true });
    }
Run Code Online (Sandbox Code Playgroud)

真棒.但是,当我使用相同的方案处理put(更新现有的家)时......

    [HttpPut]
    public ActionResult Index(Home home)
    {
        //update existing home in the db

        return Json(new { success = true });
    }
Run Code Online (Sandbox Code Playgroud)

我们遇到了一个问题.Post和Put的方法签名是相同的,当然C#不喜欢.我可以尝试一些方法,比如在签名中添加伪参数,或者更改方法名称以直接反映CRUD.但这些都是黑客或不受欢迎的.

在这里开始保存RESTful,CRUD样式控制器的最佳实践是什么?

Mat*_*eer 12

这是我所知道的最佳解决方案:

[HttpPut]
[ActionName("Index")]
public ActionResult IndexPut(Home home) 
{
     ...
}
Run Code Online (Sandbox Code Playgroud)

基本上ActionNameAttribute是为了处理这些场景而创建的.