asp.net - Web API 和更新插入

标签 asp.net asp.net-web-api

我正在使用 Web API,并且正在尝试创建一个执行更新插入的操作。

我正在传递用户的名字和姓氏,如果该组合存在于我的表中,我想更新该用户。如果该组合不存在,我想创建该用户。 (是的,这是人为的,但对于我正在构建的盲品酒派对应用程序,安全性不是必需的)

鉴于 Web API 已分别映射 POST 和 PUT 来创建和更新操作,感觉这里有点摩擦。我只使用 POST 操作,我应该以其他方式执行此操作吗?

    // POST api/User
    [ResponseType(typeof(User))]
    public async Task<IHttpActionResult> PostUser(User user)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var current = await db.Users.FirstOrDefaultAsync(u => u.FirstName == user.FirstName && u.LastName == user.LastName);
        int id;
        if (current == null)
        {
            db.Users.Add(user);;
            await db.SaveChangesAsync();
            id = user.ID;
        }
        else
        {
            id = current.ID;
            //Do some updates
            current.Prop1 = "val";
            await db.SaveChangesAsync();
            user = current;
        }

        return CreatedAtRoute("DefaultApi", new { id = id }, user);
    }

我想,另一种选择是让客户端决定是否需要进行插入或更新。这将需要另一个 Web API 调用来确定对象是否存在,然后使用适当的 HTTP 动词来使用适当的 Web API。

最佳答案

虽然没有官方标准,但我愿意付出两分钱。

您应该使用 PUT 而不是 POST 进行更新插入。请参阅this specification here

PUT 用于幂等操作或其中多次发送请求并不重要但结果始终相同的操作。

根据上面的规范:

If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.

就像我说的,这只是我的意见。如果您查看其他一些主要的 RESTful API,它们的做法有所不同。例如,Salesforce REST API 使用 PATCH 方法进行更新插入。

关于asp.net - Web API 和更新插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20861870/

相关文章:

asp.net - 从 Azure Blob 下载文件

c# - 如何停止文本框上的CSS类

c# - ASP.NET MVC 消息处理程序与 Web API 消息处理程序

asp.net-web-api - 网址链接() : Route cannot be found when using attribute routing

c# - Web API 通用操作

asp.net-web-api - 成员(member)重新启动用 Simple Injector 替换 Ninject

asp.net - MVC 4 - DataAnnotations - 类型验证

javascript - 编写新文本时更改文本框文本的颜色

c# - 未检测到复选框 == true

.net - 使用来自 webapi 的 HttpClient 使用 xml