假设我有一个 Controller 来处理“家庭”的 CRUD 场景。 Get 看起来像这样:
[HttpGet]
public ActionResult Index(int? homeId)
{
Home home = homeRepo.GetHome(homeId.Value);
return Json(home, JsonRequestBehavior.AllowGet);
}
到现在为止还挺好。然后我添加一个 post Action 来添加新 Action 。
[HttpPost]
public ActionResult Index(Home home)
{
//add the new home to the db
return Json(new { success = true });
}
惊人的。但是当我使用相同的方案来处理看跌期权(更新现有房屋)时......
[HttpPut]
public ActionResult Index(Home home)
{
//update existing home in the db
return Json(new { success = true });
}
我们遇到了一个问题。 Post 和 Put 的方法签名是相同的,这当然是 C# 不喜欢的。我可以尝试一些事情,比如在签名中添加虚假参数,或者更改方法名称以直接反射(reflect) CRUD。但是,这些是hacky或不受欢迎的。
在这里保留 RESTful、CRUD 风格的 Controller 的最佳实践是什么?
最佳答案
这是我所知道的最佳解决方案:
[HttpPut]
[ActionName("Index")]
public ActionResult IndexPut(Home home)
{
...
}
ActionNameAttribute
基本上是为了处理这些场景而创建的。
关于asp.net-mvc - 具有不同 Http 方法但参数相同的 RESTful Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4939438/