我们正在使用 .NET Core 3.1、Microsoft.AspNetCore.JsonPatch 3.1.27 和AutoMapper 12.0.1.
我们正在开发一个 REST API。它公开了一些用于使用 HTTP PATCH 动词更新实体的端点。这些控制器操作接受 DTO 类的 JSON 补丁文档,例如。
JsonPatchDocument<RestApiRequest>
.
[HttpPatch]
public IActionResult UpdateCustomer(JsonPatchDocument<RestApiRequest> req)
{
return Ok();
}
public class RestApiRequest
{
public string CustomerName { get; set; }
public string CompanyAddress { get; set; }
}
我们的 2 个数据库模型看起来像这样(简化):
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public Company Company { get; set; }
}
public class Company
{
public int Id { get; set; }
public string Address { get; set; }
}
我们这样配置 AutoMapper:
// RestApiRequest.CompanyAddress is mapped to Address
CreateMap<RestApiRequest, Company>()
.ForMember(x => x.Address, x => x.MapFrom(y => y.CompanyAddress));
// RestApiRequest.CustomerName is mapped to Name
CreateMap<RestApiRequest, Customer>()
.ForMember(x => x.Name, x => x.MapFrom(y => y.CustomerName));
CreateMap<JsonPatchDocument<RestApiRequest>, JsonPatchDocument<Company>>();
CreateMap<JsonPatchDocument<RestApiRequest>, JsonPatchDocument<Customer>>();
CreateMap<Operation<RestApiRequest>, Operation<Company>>();
CreateMap<Operation<RestApiRequest>, Operation<Customer>>();
当客户端向其中一个控制器操作发送 HTTP 请求时,我们会得到一个类似于
patch
变量中的对象。然后,我们尝试将它从JsonPatchDocument<RestApiRequest>
映射到JsonPatchDocument<Customer>
并保存到mappedPatch
变量:
var patch = new JsonPatchDocument<RestApiRequest>()
.Replace(x => x.CustomerName, "New customer name")
.Replace(x => x.CompanyAddress, "New company address");
var mappedPatch = _mapper.Map<JsonPatchDocument<RestApiRequest>, JsonPatchDocument<Customer>>(patch);
但是,
path
中的JsonPatchDocument.Operations
没有被映射。 patch
和 mappedPatch
都有相同的路径,这是不正确的:
[
{
"value":"New customer name",
"path":"/CustomerName",
"op":"replace"
},
{
"value":"New company address",
"path":"/CompanyAddress",
"op":"replace"
}
]
我希望
mappedPatch
的路径是/Name
和/Company/Address
.