Skip to content

HttpClient from WebApplicationFactory returns "415 Unsupported Media Type" on HttpMethod.PATCH  #35770

Open
@lobodava

Description

@lobodava

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<Startup> fixture)
{
    Client = fixture.CreateClient();
}

private async Task PatchAsync<T>(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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templatesfeature-mvc-testingMVC testing packageinvestigate

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions