我正在尝试在 ASP.NET Core 中使用JsonPatch来处理模型的部分更新,但是在将 PATCH 发送到 Web API 控制器操作时遇到绑定问题:
我正在使用一个小型库来发出 PATCH 请求:
axios
.patch('http://localhost:8090/api/characters/1', { bookId: 1, name: 'Bob'})
.then(function () { /*...*/ })
.catch(function() { /*...*/ });
这是原始请求:
PATCH http://localhost:8090/api/characters/6 HTTP/1.1
Host: localhost:8090
Connection: keep-alive
Content-Length: 30
Accept: application/json, text/plain, */*
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:3000/library/book/2/character/6
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-AU,en;q=0.8,ru;q=0.6
{"bookId":1,"name":"Bob"}
我的视图模型:
public class UpdateCharacterViewModel
{
public string Name { get; set; }
}
最后,Web API 操作:
[Route("~/api/[controller]/{characterId}")]
[HttpPatch]
public IActionResult Update(int characterId, [FromBody]UpdateCharacterViewModel viewModel, [FromBody]JsonPatchDocument<UpdateCharacterViewModel> patch)
{
// viewModel is bound correctly but patch is NULL
// ...
}
我发现这patch
是通过 as NULL
,表明绑定存在问题。为了检查请求没有问题,我添加了viewModel
并发现它正确绑定 - 填充UpdateCharacterViewModel
可用于操作。
我在这里做错了什么?