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?