HttpClient from WebApplicationFactory returns "415 Unsupported Media Type" on HttpMethod.PATCH
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
Description
When try to use HttpClient from WebApplicationFactory (Microsoft.AspNetCore.Mvc.Testing, Version=5.0.9.0) with xUnit, the PATCH http method always returns "415 Unsupported Media Type" status code.
For example, here is the ASP.NET Core 5.0 Web Api Contoller:
```
public class HomeController : ControllerBase
{
[HttpPatch("entities")]
public async Task EntitiesPartialUpdate(Entity[] entities)
{
await EntitiesPartialUpdate(entities);
}
}
```
And here is the xUnit test to call the above http method:
```
private readonly HttpClient Client;
public MyTests(WebApplicationFactory fixture)
{
Client = fixture.CreateClient();
}
private async Task PatchAsync(string url, T data)
{
var dataJson = JsonSerializer.Serialize(data);
var requestBody = new StringContent(dataJson, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Patch, url) { Content = requestBody };
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.ApiKey);
var response = await Client.SendAsync(request);
if (response.StatusCode == HttpStatusCode.UnsupportedMediaType)
{
// always get here
}
}
```
If to call the Patch controller methods from regular http client like Swagger or Postman, this Patch methods work well and without any bug, however calling these Patch methods from HttpClient withing the xUnit tests fail in any configuration of requests. Client.SendAsync and Client.PatchAsync fail identically.
Calling of the other http methods like Post, Get, Put within the xUnit test succeed as well.
- ASP.NET Core version: 5.0
- The IDE : Microsoft Visual Studio Community 2019, Version 16.11.1
Contributor guide
Research direction
Start with the WebApplicationFactory and xUnit test shown, then compare HttpClient.SendAsync and PatchAsync for the PATCH request. Reproduce the ASP.NET Core 5.0 controller scenario and inspect why the application returns 415 despite the JSON content type; done means the PATCH request succeeds in the test as it does through Swagger or Postman.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- api, backend, testing
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100