2

我有一个模型,

public class Order
{
    public Guid Id { get; set; }
    public IEnumerable<string> ItemIds { get; set; }
    public string Currency { get; set; }
}

和一个存储库,

public interface IOrderRepository
{
    IEnumerable<Order> Get();
    Order Get(Guid id);
    void Add(Order order);
    void Update(Guid id, Order order);
    // other irrelevant code has been deleted for simplicity
}

public class MemoryOrderRepository : IOrderRepository
{
    private readonly IList<Order> _orders = new List<Order>();
    public IEnumerable<Order> Get() => _orders;

    public Order Get(Guid id) => _orders.FirstOrDefault(o => o.Id == id);
    public void Add(Order order) => _orders.Add(order);

    public void Update(Guid id, Order order)
    {
        var target = _orders.FirstOrDefault(o => o.Id == id);
        if (target != null) target.ItemIds = order.ItemIds;
    }
    // other irrelevant code has been deleted for simplicity
}

已注册Startup.cs如下。

    public void ConfigureServices(IServiceCollection services) =>
        services.AddSingleton<IOrderRepository, MemoryOrderRepository>()
                .AddControllers()
                .AddNewtonsoftJson();

其他相关的 nuget 包已经安装如下。

<PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="3.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />

下面给出了一个测试控制器。

[Route("api/[controller]")]
[ApiController]
public class OrderController : ControllerBase
{
    private readonly IOrderRepository repo;

    public OrderController(IOrderRepository repo)
    {
        this.repo = repo;
    }

    [HttpGet]
    public IActionResult Get() => Ok(repo.Get());

    [HttpGet("{id:guid}")]
    public IActionResult Get(Guid id) => Ok(repo.Get(id));

    [HttpPost]
    public IActionResult Post(Order order)
    {
        Order target = new Order()
        {
            Id = Guid.NewGuid(),
            ItemIds = order.ItemIds
        };

        repo.Add(target);

        return CreatedAtAction(nameof(Get), new { id = target.Id }, null);
    }

    [HttpPatch("{id:guid}")]
    public IActionResult Patch(Guid id, JsonPatchDocument<Order> order)
    {
        Order target = repo.Get(id);
        if (target == null)
            return NotFound(new { Message = $"Item with id {id} does not exist." });


        order.ApplyTo(target);
        repo.Update(id, target);
        return Ok();
    }

    // other irrelevant code is deleted for simplicity
}

使用 Postman,我通过先向服务器发送 POST 动词然后通过发送 GET 动词来确认结果来成功创建新订单,如下所示。

在此处输入图像描述

在此处输入图像描述

问题

我尝试使用以下内容部分更新订单,但失败了。

在此处输入图像描述

错误信息是

JSON 补丁文档格式错误,无法解析。

出了什么问题以及如何解决?

代替

{
    "ItemIds": ["xyz","123"]
}

我也试过

{
    "op":"replace",
    "path":"/ItemIds",
    "value": ["xyz","123"]
}

两者都没有帮助。

4

1 回答 1

5

根据 json patch 的文档,您需要传递一个操作数组而不是单个对象,就像这样

[
  {
    "op":"replace",
    "path":"/ItemIds",
    "value": ["xyz","123"]
  }
]
于 2020-01-19T22:45:27.820 回答