加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – Web API和Upserts

发布时间:2020-12-16 06:27:24 所属栏目:asp.Net 来源:网络整理
导读:我正在使用Web API,我正在尝试创建一个执行upsert的操作. 我传入用户的名字和姓氏,如果我的表中存在该组合,我想更新该用户.如果组合不存在,我想创建该用户. (是的,这是做作的,但是对于我正在建造的盲品酒品牌派对应用程序,不需要安全性) 鉴于Web API已分别映
我正在使用Web API,我正在尝试创建一个执行upsert的操作.

我传入用户的名字和姓氏,如果我的表中存在该组合,我想更新该用户.如果组合不存在,我想创建该用户. (是的,这是做作的,但是对于我正在建造的盲品酒品牌派对应用程序,不需要安全性)

鉴于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.

解决方法

虽然没有官方标准,但我会给我两分钱.

对于upsert,您应该使用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方法进行upsert.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读