Home > Software engineering >  HttpClient returns BadRequest when expected UnsupportedMediaType
HttpClient returns BadRequest when expected UnsupportedMediaType

Time:02-22

I have an action in a controller that accepts an IFormFile and does some logic with it. When I try to send wrong content from another application, I get UnsupportedMediaType, this is the expected behavior. But when I do the same in unit tests with HttpClient, it returns BadRequest, if the request content type is wrong, not UnsupportedMediaType.

Is it normal? How can I change this behavior to return UnsupportedMediaType, as expected?

Controller action:

public async Task<IActionResult> Foo([FromForm] IFormFile file)
{
    return Ok();
}

Test:

[Test]
public async Task Foo()
{
    var json = JsonSerializer.Serialize(new object());
    var httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

    var httpResponse = await _httpClient.PostAsync(Url, httpContent);
    
    // Expected: UnsupportedMediaType
    // But was:  BadRequest
    Assert.AreEqual(System.Net.HttpStatusCode.UnsupportedMediaType, response.StatusCode);
}

Upd:

I read the response message, now the things got clearer:

{
    "type":"https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title":"One or more validation errors occurred.",
    "status":400,
    "traceId":"00-f3d8b7fb42d2fdf01d74a64d27c75b7b-6cfd3b2226d61981-00",
    "errors":{"file":["The file field is required."]}
}

I guess, I need to change the json I'm sending. But I'm not sure how. Doing something like this doesn't do the trick:

var json = JsonSerializer.Serialize(new { file = new { test = "test" } });

Upd2:

I decided to use the attribute [Consumes("multipart/form-data")] on the controller. Now requests with wrong data type return NotFound, and HttpClient returns NotFound as well. It's fine for me, but the question about UnsupportedMediaType is open anyway.

CodePudding user response:

Your test is incorrect. You're just posting an empty object as JSON. You need to send an actual file so that the endpoint is hit.

Use MultipartFormDataContent to post a file to the endpoint. Refer to this StackOverflow question:

CodePudding user response:

This error tells you that you are using POST request, but controller expects GET. Try to use [HttpPost] in controller:

[HttpPost]
public async Task<IActionResult> Foo([FromForm] IFormFile file)
{
    return Ok();
}
  • Related