1
votes

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?

2
What does the client code look like that receives the HttpResponseMessage? For me, when I do response.Content = new StringContent(request.Error.Message); on the server side, I can then do the following on the client side var message = await response.Content.ReadAsStringAsync();hvaughan3

2 Answers

1
votes

You have to add Response.StatusCode to the request pipeline:

response.StatusCode = request.Error.StatusCode;
Response.StatusCode = request.Error.StatusCode;

Else, the framework assumes a 200 OK.

0
votes

Please use this code block for error part.

if (request.Error != null)
{
   response.ReasonPhrase= request.Error.Message;
   response.StatusCode = HttpStatusCode.BadRequest;
}

I can see the response like this.

StatusCode: 400, ReasonPhrase: 'Bad Msg', Version: 1.1, Content: , Headers: { }