gpt4 book ai didi

使用 HTTPClient 的 C# HTTP PATCH

转载 作者:行者123 更新时间:2023-12-04 17:26:18 29 4
gpt4 key购买 nike

我已经在 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());
}
在示例中,我创建了一个带有操作列表的 JsonPatchDocument,将其序列化为 JSON,然后使用端点的 URL 使用 HTTP 客户端执行 PatchAsync。
所以我的问题是我应该修补的对象的形状是什么,并且我在一般情况下这样做是正确的?
我尝试发送如下图所示的 EntryModel,但是 patchDocument.Operations 有一个空列表。
enter image description here
谢谢,
缺口

最佳答案

我最终通过做几件事来解决我的问题:

  • 没有依赖,JsonPatchDocument 似乎无法工作services.AddControllers().AddNewtonsoftJson();在 Startup.cs 中。这是来自 Nuget 包`Microsoft.AspNetCore.Mvc.Newtonsoft.json。
  • 有一种比@Neil 的答案更简单的方法来创建数组。这是: var patchDoc = new JsonPatchDocument<EntryModel>().Replace(o => o.EntryTypeId, 5);
  • 您需要这种特定的媒体类型:var content = new StringContent(JsonConvert.SerializeObject(patchDoc), Encoding.UTF8, "application/json-patch+json");

  • 这是完整的代码:
    /// <summary>
    /// Verify PUT /Entrys is working and returns updated records
    /// </summary>
    [Fact]
    public async Task Patch()
    {
    var patchDoc = new JsonPatchDocument<EntryModel>()
    .Replace(o => o.EntryTypeId, 5);

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

    // Assert
    Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
    Assert.True(httpResponse.IsSuccessStatusCode);
    }

    /// <summary>
    /// Endpoint to do partial update
    /// </summary>
    /// <returns></returns>
    [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));

    // Apply changes
    patchDocument.ApplyTo(existingEntry);

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

    return Ok();
    }

    关于使用 HTTPClient 的 C# HTTP PATCH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63054934/

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