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
.
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).
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.
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.
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.
Try this one. response.Content.ReadAsAsync<HttpError>().Result.Message;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With