使用 Postman 将 PATCH 发送到 Asp.net Core webapi 时出错

An error when sending PATCH with Postman to Asp.net Core webapi

我有模型,

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 动词确认结果,成功创建了一个新订单。

问题

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

错误信息是

The JSON patch document was malformed and could not be parsed.

有什么问题以及如何解决?

而不是

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

我也试过了

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

两者都无济于事。

根据 docs for json 补丁,您需要传递一组操作而不是单个对象,就像这样

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