C# HttpClient 在 Patch 请求中返回 415 Unsupported media type

标签 c# patch asp.net-core-3.1 json-patch http-status-code-415

我们有一个 .netcore 3.1 ApiController 和一个端点监听 PATCH 请求,并定义了一个我们用于集成/API 测试的测试服务器。

使用 Postman 发送的 PATCH 请求工作正常,但在 XUnit 测试中通过 HttpClient 发送的请求因 415 Unsupported media type 而失败。

postman 补丁请求:
除了不记名 token 和内容类型:“应用程序/json”之外没有特定的 header

在测试中,我们使用 WebApplicationFactory,它是我们的 HttpClient 的 factory.CreateClient()。

Json 序列化不应该是问题,因为我通过调试器查看了内容,它似乎被序列化了。

此外,我们的 POST 方法使用完全相同的代码完全开箱即用(将“PATCH”替换为“POST”等)

期待一些建议。另外,如果您需要更多信息,请告诉我。非常感谢。

Controller :

[HttpPatch("{id}")]
public async Task<ActionResult<Unit>> Edit(Edit.Command request)
{
     return await Mediator.Send(request);
}

命令:
public class Command : IRequest
{
      public string Id { get; set; }

      public JsonPatchDocument<ObjectDTO> PatchDocument { get; set; }
}

测试:
[InlineData(/* inline data goes here */)]
public async void TestEdit_Ok(/* required parameters for the test */)
{
    var request = new HttpRequestMessage(new HttpMethod("PATCH"), url));
    request.Headers.Add("Authorization", "Bearer " + token);

    /* create patch document logic goes here */

    var command = new Command()
    {
          Id = target,
          PatchDocument = patchDocument,
    };

    _testHelper.AddJsonContent(request, command);

    // Act
    var response = await _client.SendAsync(request);

    // Assert
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

其中辅助方法 AddJsonContent 定义为:
public void AddJsonContent(HttpRequestMessage request, object content)
{
      request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
      string serializedContent = JsonConvert.SerializeObject(content);
      request.Content = new StringContent(serializedContent, Encoding.UTF8, "application/json");
}

最佳答案

问题在 Asp.Net Core 5.0 中得到确认
(我确认的问题——我和话题发起人有同样的问题)
当将 xUnit 与 WebApplicationFactory 和 factory.CreateClient() 用于 HttpClient 时,PATCH 方法返回“415 Unsupported Media Type”状态。
不同组合中所有可能的尝试都会导致 415 状态。
但是,其他方法(如 Swagger 和 Postman)与 PATCH 方法配合得很好。
只有 xUnit(或 WebApplicationFactory)PATCH 方法失败。
最后,为了进行测试,我们使用 POST 方法做了一个解决方法,其中包含 /with-partial-update作为路线部分。
This bug is reported to aspnetcore repository

关于C# HttpClient 在 Patch 请求中返回 415 Unsupported media type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61257614/

相关文章:

C#,System.Timers.Timer,每分钟与系统时钟同步运行

Git 错误 : previous rebase directory . git/rebase-apply 仍然存在但给出了 mbox

git - 如何将 git 补丁从一个存储库应用到另一个存储库?

c++ - 有没有办法从 C++ 中区分文件?

c# - 何时在 EF Core 中使用异步方法?

javascript - 如何设置 @Html.DropDownList 的名称?

c# - 从 HttpResponseException 中提取 HttpError

c# - 类型 xxxx 不应使用 xmlinclude 或 soapinclude

javascript - 未捕获的类型错误 : Cannot read property 'locals' of undefined

c# - 参数化 Where IN 子句不适用于 CosmosClient QueryDefinition 对象