Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the error message from an HttpResponse object in WebAPI?

I have a controller that generates an exception from the following code with the following message:-

public HttpResponseMessage PutABook(Book bookToSave)
{
   return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Permission");
}

am testing this method with the following code:-

var response = controller.PutABook(new Book());
Assert.That(response.StatusCode,Is.EqualTo(HttpStatusCode.Forbidden));
Assert.That(response.Content,Is.EqualTo("No Permission"));

But am getting an error that the content is not "No Permission". It seems I can't cast the response to an HttpError either to get the message content "No Permission". The status code is returned fine. Just struggling to get the message content.

like image 292
TDD Junkie Avatar asked Jun 13 '13 07:06

TDD Junkie


People also ask

How do I return a message in Web API?

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response. Convert directly to an HTTP response message. Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. Write the serialized return value into the response body; return 200 (OK).

What is an HTTPResponse object?

The HTTPResponse object contains all outgoing response data. It consists of the HTTP status code and message, the HTTP headers, and any response body data. HTTPResponse also contains the ability to stream or push chunks of response data to the client, and to complete or terminate the request.

How do I set HttpResponseMessage content?

Several months ago, Microsoft decided to change up the HttpResponseMessage class. Before, you could simply pass a data type into the constructor, and then return the message with that data, but not anymore. Now, you need to use the Content property to set the content of the message.


2 Answers

As you figured in your comment, you could either use response.Content.ReadAsAsync<HttpError>() or you could also use response.TryGetContentValue<HttpError>(). In both these cases, the content is checked to see if its of type ObjectContent and the value is retrieved from it.

like image 135
Kiran Avatar answered Oct 16 '22 11:10

Kiran


Try this one. response.Content.ReadAsAsync<HttpError>().Result.Message;

like image 23
aiapatag Avatar answered Oct 16 '22 12:10

aiapatag