如何从WebAPI中的HttpResponse对象获取错误消息? [英] 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"));
但是却收到一个错误,内容不是没有权限".看来我也无法将响应转换为 HttpError
来获取消息内容"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
.
推荐答案
正如您在注释中所指出的,您可以使用 response.Content.ReadAsAsync< HttpError>()
或也可以使用 response.TryGetContentValue< HttpError>()
.在这两种情况下,都将检查内容以查看其内容是否为 ObjectContent
类型,并从中获取值.
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.
这篇关于如何从WebAPI中的HttpResponse对象获取错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!