【问题标题】:MVC Web Api difference between HttpPost and HttpPutHttpPost 和 HttpPut 之间的 MVC Web Api 区别
【发布时间】:2019-12-09 08:48:48
【问题描述】:

我是 MVC Web Api 的新手。

我想要两种不同的方法。

PUT localhost/api/user - 修改用户

POST localhost/api/user - 添加用户

所以我的ApiController 看起来像这样:

    [HttpPost]
    public bool user(userDTO postdata)
    {
        return dal.addUser(postdata);
    }

    [HttpPut]
    public bool user(userDTO postdata)
    {
        return dal.editUser(postdata);
    }

但是我的 HttpPut 方法说“已经定义了一个名为 user 的成员具有相同的参数类型。

[HttpPost][HttpPut] 不应该使方法独一无二吗?

【问题讨论】:

标签: c# asp.net-web-api


【解决方案1】:

HttpPost和HttpPut的MVC Web Api区别

HTTP PUT 应该接受请求的主体,然后将其存储在由 URI 标识的资源中。

HTTP POST 更通用。它应该在服务器上启动一个动作。该操作可能是将请求正文存储在由 URI 标识的资源中,也可能是不同的 URI,也可能是不同的操作。

PUT 就像文件上传。对 URI 的放置完全影响该 URI。对 URI 的 POST 可能会产生任何影响。

已经定义了一个名为 user 且参数类型相同的成员

您不能在同一范围内拥有多个具有相同签名的方法,即相同的返回类型和参数类型。

[HttpPost]
public bool User(userDTO postdata)
{
    return dal.addUser(postdata);
}

[HttpPut]
[ActionName("User")]
public bool UserPut(userDTO postdata)
{
    return dal.editUser(postdata);
}

更多相关答案。检查这个。 GET and POST methods with the same Action name in the same Controller

【讨论】:

    【解决方案2】:

    当您有 2 个具有相同名称和相同签名的方法时,没有属性可以使您的方法独一无二。

    你的解决方案看起来像这样。

        [HttpPost]
        public bool User(userDTO postdata)
        {
            return dal.addUser(postdata);
        }
    
        [HttpPut]
        [ActionName("User")]
        public bool UserPut(userDTO postdata)
        {
            return dal.editUser(postdata);
        }
    

    P.S:命名方法的约定是在命名方法时应该使用 PascalCase 并使用动词。

    Method Naming Guidelines

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 2013-05-07
      • 1970-01-01
      • 2020-07-28
      • 2016-11-14
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多