.NET API 更新包括 ID [英] .NET API Update Includes ID
问题描述
我来自 Ruby on Rails API 背景,但目前正在研究 .NET C# WebAPI.我熟悉 C# 和 .NET 网络表单.
I come from a Ruby on Rails API background, but am currently working on a .NET C# WebAPI. I am familiar with C# and .NET webforms.
我正在尝试设置将更新数据库中的记录的 PUT 请求.脚手架方法覆盖所有字段,而我只想更新通过 PUT 传递的字段.我尝试使用以下代码:
I'm attempting to set up a PUT request that will update a record in the db. The scaffolded method overwrites all the fields, whereas I want to simply update just the fields passed through the PUT. I attempted with the below code:
// 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 如下:
However, the method fails on db.SaveChanges()
as it cannot overwrite 'id', which is a key. The put request is of content-type: application/json
and the json is below:
{
"preferredEmailUpdates":"true"
}
这需要适用于所有字段并接受空条目.所以下面的内容也是有效的,应该用 null 更新外地电话.
This needs to work for all fields and accept null entries. So the below is valid as well, and should update the field phone with null.
{
"preferredEmailUpdates":"true",
"phone":null
}
如何在不更新密钥的情况下更新这些值?
How do I update these values, while not updating the key?
推荐答案
您可以考虑使用 PATCH
HTTP 动词和 Delta
对象.
You can consider using the PATCH
HTTP verb and a Delta<T>
object.
[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 资源.
这篇关于.NET API 更新包括 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!