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

An error when sending PATCH with Postman to Asp.net Core webapi(使用 Postman 向 Asp.net Core webapi 发送 PATCH 时出错)
本文介绍了使用 Postman 向 Asp.net Core webapi 发送 PATCH 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模特,

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包已经安装如下.

Additional relevant nuget packages are already installed as follows.

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

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

A testing controller is given as follows.

[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 动词确认结果,如下所示.

Using Postman, I successfully created a new order by sending POST verb to the server first and then confirming the result by sending GET verb as follows.

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

I attempted to partially update the order with the following but failed.

错误信息是

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

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

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

What is wrong and how to fix it?

代替

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

我也试过了

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

两者都没有帮助.

推荐答案

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

According to the docs for json patch you need to pass an array of operations instead of single object, like so

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

这篇关于使用 Postman 向 Asp.net Core webapi 发送 PATCH 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)