微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-core – 在JsonPatchDocument中使用.Net Core Web API

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

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

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

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

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

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

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

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

解决方法

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

[
  { "op": "replace",]

然后在调用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; }
}

希望这可以帮助.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐