我有一个模型,
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"]
}
两者都不帮忙。
2条答案
按热度按时间zed5wv101#
根据json补丁的文档,您需要传递一个操作数组,而不是单个对象,如下所示
iszxjhcz2#
你试过去掉方括号吗?我也遇到过类似的问题,但是没有。