Reputation: 243
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
.
Upvotes: 24
Views: 49416
Reputation: 350
read error message this way.
var ErrMsg = JsonConvert.DeserializeObject<dynamic>(response.Content.ReadAsStringAsync().Result);
Upvotes: 4
Reputation: 246
You can try the following:
var errorContent = await response.Content.ReadAsAsync<HttpError>();
Assert.That(errorContent.Message,Is.EqualTo("No Permission"));
Upvotes: 4
Reputation: 3430
Try this one. response.Content.ReadAsAsync<HttpError>().Result.Message;
Upvotes: 7
Reputation: 57949
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.
Upvotes: 21