如何从WebAPI中的HttpResponse对象获取错误消息?

我有一个控制器,从以下代码生成exception,并带有以下消息: –

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

我正在使用以下代码测试此方法: –

 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”。 状态代码返回正常。 只是努力获取message content

正如您在评论中所述,您可以使用response.Content.ReadAsAsync() ,也可以使用response.TryGetContentValue() 。 在这两种情况下,都会检查内容以查看其类型为ObjectContent并从中检索值。

试试这个。 response.Content.ReadAsAsync().Result.Message;

您可以尝试以下操作: var errorContent = await response.Content.ReadAsAsync(); Assert.That(errorContent.Message,Is.EqualTo("No Permission")); var errorContent = await response.Content.ReadAsAsync(); Assert.That(errorContent.Message,Is.EqualTo("No Permission"));