asp.net-mvc - 具有不同 Http 方法但参数相同的 RESTful Controller

标签 asp.net-mvc rest crud

假设我有一个 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/

相关文章:

java - Spring Roo 不生成 CRUD

java - OpenXava - 创建包含所有模块的列表

java - 在android中读取数据sqlite失败

java - 为什么我的 HttpPost 请求被分成两个请求?

c# - 在此上下文中没有响应

asp.net-mvc - 如何使用 ASP.NET MVC 和表单例份验证创建单页应用程序 (SPA)?

javascript - 在客户端使用 Mailgun RestFUL

amazon-web-services - AWS API Gateway REST API 是否没有设置来禁用 CloudFormation 模板中的执行 api 端点?

java - Spring Boot Rest API - 输入文件+端点

sql - Linq to SQL Group by 和 Sum in Select