如何在 ASP.NET Core 2.0 Web API 中配置和使用 Microsoft.AspNetCore.JsonPatch

fso*_*o94 2 c# asp.net json json.net

我正在我的 ASP.NET Web API 控制器中创建一个 HTTP Partial 方法,我阅读了这个文档http://benfoster.io/blog/aspnet-core-json-patch-partial-api-updates关于如何实现 HTTP Partial 方法在控制器中。当我点击 HTTP Partial 端点时出现异常在此处输入图片说明

这是我的控制器中 Patch 方法的代码:

[HttpPatch("{userId}")]
public IActionResult Patch([FromRoute(Name = "userId")]Guid userId, [FromBody] JsonPatchDocument<User> userProperties)
{
    var indexOfUserToPartiallyUpdate = UsersInMemory.List.FindIndex(user => user.Id == userId);

    if (indexOfUserToPartiallyUpdate == -1)
    {
        return BadRequest($"user with {userId} not found.");
    }

    var originalUser = UsersInMemory.List[indexOfUserToPartiallyUpdate];

    userProperties.ApplyTo(UsersInMemory.List[indexOfUserToPartiallyUpdate], ModelState);

    if (!ModelState.IsValid)
    {  
        return new BadRequestObjectResult(ModelState);
    }

    var model = new
    {
        beforePatch = originalUser,
        afterPatch = UsersInMemory.List[indexOfUserToPartiallyUpdate]
    };

    return Ok(model);
}
Run Code Online (Sandbox Code Playgroud)

这是我在 HTTP PATCH 请求中通过邮递员发送的 JSON 正文:

在此处输入图片说明

我觉得我需要在 Startup.cs 文件中做一些事情,例如配置 JsonPatchDocument 但我不知道如何做。任何帮助深表感谢。

小智 5

我想我发现了您的问题:“请注意,即使您只发送一个操作,我们也总是发送一系列操作。”

尝试更改您的请求:

[
  {
    "op": "replace",
    "path": "/email",
    "value": "THIS_SOME_OTHER_EMAIL@gmail.com"
  }
]
Run Code Online (Sandbox Code Playgroud)