使用 HTTPClient 的 C# HTTP 补丁

nic*_*wdy 5 c# patch http-patch .net-core

我已经使用 dot net core 3.1 中的测试服务器编写了一个测试,并且正在尝试向端点发出 PATCH 请求。然而,由于我是使用 PATCH 的新手,我对如何发送端点期望的正确对象有点困惑。

[Fact]
public async Task Patch()
{
    var operations = new List<Operation>
    {
        new Operation("replace", "entryId", "'attendance ui", 5)
    };

    var jsonPatchDocument = new JsonPatchDocument(operations, new DefaultContractResolver());

        
    // Act
    var content = new StringContent(JsonConvert.SerializeObject(jsonPatchDocument), Encoding.UTF8, "application/json");
    var httpResponse = await HttpClient.PatchAsync($"v1/Entry/1", content);
    var actual = await httpResponse.Content.ReadAsStringAsync();
        
}

[HttpPatch("{entryId}")]
public async Task<ActionResult> Patch(int entryId, [FromBody] JsonPatchDocument<EntryModel> patchDocument)
{
    if (patchDocument == null)
       {
           return BadRequest();
       }

       var existingEntry = _mapper.Map<EntryModel>(await _entryService.Get(entryId));

       patchDocument.ApplyTo(existingEntry);

       var entry = _mapper.Map<Entry>(existingEntry);
       var updatedEntry = _mapper.Map<Entry>(await _entryService.Update(entryId, entry));

       return Ok(await updatedEntry.ModelToPayload());
}
Run Code Online (Sandbox Code Playgroud)

在示例中,我创建了一个包含操作列表的 JsonPatchDocument,将其序列化为 JSON,然后使用带有端点 URL 的 HTTP 客户端执行 PatchAsync。

所以我的问题是我应该修补的对象的形状是什么,并且我总体上做得正确吗?

我尝试发送 EntryModel,如下图所示,但是 patchDocument.Operations 有一个空列表。

在此输入图像描述

谢谢,尼克

Nei*_*eil 0

看一下此页面:https://learn.microsoft.com/en-us/aspnet/core/web-api/jsonpatch ?view=aspnetcore-3.1

但内容大概是这样的:

[   {
    "op": "add",
    "path": "/customerName",
    "value": "Barry"   },   {
    "op": "add",
    "path": "/orders/-",
    "value": {
      "orderName": "Order2",
      "orderType": null
    }   } ]
Run Code Online (Sandbox Code Playgroud)