0

I have a controller action in my WebAPI server that returns a 401 Unauthorized. The action also returns other error status codes such as 401, 409 and 500 as well as 200. All status codes add a DTO serialized to JSON all are working as expected.

For 401 I'm doing:

return Unauthorized(new UnauthorizedError() {
    Id = 1, //int
    Error = Error.UserNotFound, //enum
    Message = "User not found"  //string
});

The clients handles the 401 and reads the content as Unauthorized:

if (response.StatusCode == HttpStatusCode.Unauthorized)
{
    var result = await response.Content.ReadAsAsync<UnauthorizedError>(ct);
}

But just for these status code, I'm getting an exception:

No MediaTypeFormatter is available to read an object of type 'UnauthorizedError' from content with media type 'text/html'.

The app is running in IIS. Might it be the case that IIS is overriding the response type for 401? Is there a way to force a json response type on this action?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • IIS has some stupid behavior of overriding the default error response if response body is below a arbitrary threshold. Try this [web.config setting](https://stackoverflow.com/a/702809) and see if it helps. – Mat J Feb 17 '23 at 05:02
  • could you able to specify the return type of the controller? – Jeevan ebi Feb 20 '23 at 07:49
  • The problem occurs when running locally from Visual Studio using IIS Express. Everything works fine when the app is published in IIS. – Ivan-Mark Debono Feb 20 '23 at 09:02

1 Answers1

0

It seems that the default content-type of response header is text/html, while the goal response type is JSON. I created a project and tried to reproduce your issue. When I running it locally from Visual Studio, I did not get the same error message. So I think forcing the response type to JSON for this action may be helpful. I am using this code:

if (responseStatusCode == HttpStatusCode.Unauthorized)
{
    var result = await response.Content.ReadFromJsonAsync<UnauthorizedError>();
}

Just try changing the ReadAsAysnc to ReadFromJsonAsync.

Xiaotian Yang
  • 499
  • 1
  • 2
  • 7