【问题标题】:How to configure and use Microsoft.AspNetCore.JsonPatch in ASP.NET Core 2.0 Web API如何在 ASP.NET Core 2.0 Web API 中配置和使用 Microsoft.AspNetCore.JsonPatch
【发布时间】:2018-05-02 04:46:33
【问题描述】:

我正在我的 ASP.NET Web API 控制器中创建一个 HTTP Partial 方法,我阅读了这篇文档http://benfoster.io/blog/aspnet-core-json-patch-partial-api-updates,了解如何在控制器中实现 HTTP Partial 方法。当我点击显示 的 HTTP 部分端点时出现异常

这是我在控制器中的 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);
}

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

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

【问题讨论】:

    标签: c# asp.net json json.net


    【解决方案1】:

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

    尝试更改您的请求:

    [
      {
        "op": "replace",
        "path": "/email",
        "value": "THIS_SOME_OTHER_EMAIL@gmail.com"
      }
    ]
    

    【讨论】:

    • 好的,谢谢瓦迪姆。下班后我会尝试一下,如果这有解决方案,我会告诉你。
    • 这对瓦迪姆有效。非常感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 2017-11-01
    • 2018-03-18
    • 2019-05-16
    相关资源
    最近更新 更多