gpt4 book ai didi

asp.net-core - 将 .Net Core Web API 与 JsonPatchDocument 结合使用

转载 作者:行者123 更新时间:2023-12-02 01:52:52 24 4
gpt4 key购买 nike

我正在使用 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 对象看起来像是该补丁不起作用。我相信我需要使用它进行转换

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

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

最佳答案

我使用 ASP.NET Core 1.0 版本创建了以下示例 Controller 。如果我发送您的 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; }
}

希望这有帮助。

关于asp.net-core - 将 .Net Core Web API 与 JsonPatchDocument 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36767759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com