I'm trying to return an error message with HttpResponseMessage and all I'm getting is what I assume is StringContent.ToString()
. Here's my code:
HttpResponseMessage response = new HttpResponseMessage();
if (request.Error != null)
{
response.Content = new StringContent(request.Error.Message);
response.Content.Headers.ContentType = new MediaTypeHeaderValue(ContentTypes.PlainText);
response.StatusCode = request.Error.StatusCode;
}
else
{
response.Content = new ByteArrayContent(request.PhotoAsJpeg());
response.Content.Headers.ContentType = new MediaTypeHeaderValue(ContentTypes.Jpeg);
response.StatusCode = HttpStatusCode.OK;
}
The error status codes are things like 401, 404, etc. and the messages are plain text like "Photo not found" or "Bad parameters". My expectation is, when there is an error, a response with the status code (401, etc.) and a plain text error message. What I am receiving is a response in HTML with status code 200 and the following content:
StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StringContent, Headers: { Content-Type: text/plain }
How can I get the response to contain my error message?
HttpResponseMessage
? For me, when I doresponse.Content = new StringContent(request.Error.Message);
on the server side, I can then do the following on the client sidevar message = await response.Content.ReadAsStringAsync();
– hvaughan3