【问题标题】:Using .Net Core Web API with JsonPatchDocument将 .Net Core Web API 与 JsonPatchDocument 一起使用
【发布时间】:2019-12-17 19:45:06
【问题描述】:

我正在使用JsonPatchDocument 来更新我的实体,如果JSON 如下所示,这会很好用

[
  { "op": "replace", "path": "/leadStatus", "value": "2" },
]

当我创建对象时,它会使用Operations 节点对其进行转换

var patchDoc = new JsonPatchDocument<LeadTransDetail>();
patchDoc.Replace("leadStatus", statusId); 

{
  "Operations": [
    {
      "value": 2,
      "path": "/leadStatus",
      "op": "replace",
      "from": "string"
    }
  ]
}

如果 JSON 对象看起来像 Patch 不起作用。我相信我需要使用它来转换它

public static void ConfigureApis(HttpConfiguration config)
{
    config.Formatters.Add(new JsonPatchFormatter());
}

这应该解决了,问题是我使用的是 .net 核心,所以不能 100% 确定在哪里添加 JsonPatchFormatter

【问题讨论】:

    标签: asp.net-core json-patch


    【解决方案1】:

    我使用 1.0 版的 ASP.NET Core 创建了以下示例控制器。如果我发送你的 JSON-Patch-Request

    [
      { "op": "replace", "path": "/leadStatus", "value": "2" },
    ]
    

    然后在调用 ApplyTo 后,leadStatus 属性将被更改。无需配置 JsonPatchFormatter。 Ben Foster 的一篇好博文帮助我获得了更扎实的理解 - http://benfoster.io/blog/aspnet-core-json-patch-partial-api-updates

    public class PatchController : Controller
    {
        [HttpPatch]
        public IActionResult Patch([FromBody] JsonPatchDocument<LeadTransDetail> patchDocument)
        {
            if (!ModelState.IsValid)
            {
                return new BadRequestObjectResult(ModelState);
            }
    
    
            var leadTransDetail = new LeadTransDetail
            {
                LeadStatus = 5
            };
    
            patchDocument.ApplyTo(leadTransDetail, ModelState);
    
            if (!ModelState.IsValid)
            {
                return new BadRequestObjectResult(ModelState);
            }
    
            return Ok(leadTransDetail);
        }
    }
    
    public class LeadTransDetail
    {
        public int LeadStatus { get; set; }
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      • 2021-11-24
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多