无法获取Web Api 2中BadRequest的错误消息

Kun*_*osh 3 asp.net-mvc asp.net-web-api asp.net-mvc-5

在我的一种方法中,我必须IHttpActionResult从 Web API 2 中返回。成功后,它返回Ok(),或者返回BadRequest()一些消息。BadRequest我按以下方式设置消息。但问题是我无法从被调用的方法中检索错误消息。我使用的是 Visual Studio 2013 Update 4,版本是 MVC 5。

return BadRequest("Error!  Error adding the device");
Run Code Online (Sandbox Code Playgroud)

请帮忙。提前致谢。

Kun*_*osh 5

经过研究和学习,我找到了解决方案。由于这是Web API的一种方法,所以我通过我的网站调用它。我像下面这样调用它,RequestUrl这个 Web API 方法的 url 是在哪里。如果方法中有参数,我们必须将其写入查询字符串中。

HttpResponseMessage Response = null;
Response = client.GetAsync(RequestUrl).Result;
var stream = Response.Content.ReadAsStreamAsync().Result;

// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

我们还可以使用以下代码获得响应类型。

Response.ReasonPhrase
Run Code Online (Sandbox Code Playgroud)

BadRequest通过这种方式,我也可以得到这样的信息Ok。答对了 !!