How to get error message from HttpResponse object in WebAPI?

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

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

I 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 I get the error "No permission". I can't seem to respond to an HttpError to get the content of the "Without permission" message. The status code is returned in order. Just trying to get message content .

+4
source share
3 answers

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

+6
source

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

+4
source

You can try the following: var errorContent = await response.Content.ReadAsAsync<HttpError>(); Assert.That(errorContent.Message,Is.EqualTo("No Permission")); var errorContent = await response.Content.ReadAsAsync<HttpError>(); Assert.That(errorContent.Message,Is.EqualTo("No Permission"));

+1
source

Source: https://habr.com/ru/post/1485945/


All Articles