我有 Ruby on Rails API 背景,但目前正在开发 .NET C# WebAPI。我熟悉 C# 和 .NET Webform。
我正在尝试设置一个 PUT 请求来更新数据库中的记录。脚手架方法会覆盖所有字段,而我只想更新通过 PUT 传递的字段。我尝试使用以下代码:
// PUT: api/Users/5
[ResponseType(typeof(void))]
public IHttpActionResult PutUser(string id, User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
User userToUpdate = db.Users.Where(u => u.id == id).FirstOrDefault();
if (userToUpdate == null)
{
return NotFound();
}
db.Entry(userToUpdate).CurrentValues.SetValues(user);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (UserExists(id))
{
return Conflict();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
然而,该方法失败了db.SaveChanges()
因为它不能覆盖“id”,这是一个关键。 put 请求是content-type: application/json
json 如下:
{
"preferredEmailUpdates":"true"
}
这需要适用于所有字段并接受空条目。因此,下面的内容也是有效的,并且应该将现场电话更新为 null。
{
"preferredEmailUpdates":"true",
"phone":null
}
如何在不更新密钥的情况下更新这些值?
您可以考虑使用PATCH
HTTP 动词和Delta<T> https://msdn.microsoft.com/en-us/library/jj890572%28v=vs.118%29.aspx目的。
[AcceptVerbs("Patch"), ResponseType(typeof(void))]
public IHttpActionResult PatchUser(string id, Delta<Team> changes)
{
User userToUpdate = db.Users.Where(u => u.id == id).FirstOrDefault();
if (userToUpdate == null)
return NotFound();
changes.Patch(userToUpdate);
try
{
db.SaveChanges()
}
catch (DbUpdateException)
{
...
}
return StatusCode(HttpStatusCode.NoContent);
}
也可以看看使用 Delta 轻松更新 ASP.NET Web API 资源 http://www.strathweb.com/2013/01/easy-asp-net-web-api-resource-updates-with-delta/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)