How do I get the error message from an HttpRespons

2019-06-16 07:33发布

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.

3条回答
对你真心纯属浪费
2楼-- · 2019-06-16 08:06

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.

查看更多
放我归山
3楼-- · 2019-06-16 08:22

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

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-06-16 08:27

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

查看更多
登录 后发表回答