Asp.net mvc 无法在Web Api 2中获取BadRequest的错误消息

Asp.net mvc 无法在Web Api 2中获取BadRequest的错误消息,asp.net-mvc,asp.net-web-api,asp.net-mvc-5,Asp.net Mvc,Asp.net Web Api,Asp.net Mvc 5,在我的一个方法中,我必须在WebAPI 2中从那里返回IHttpActionResult。成功后,它返回Ok()或者返回BadRequest(),并显示一些消息。 我正在按以下方式设置BadRequest消息。但问题是我无法从被调用的方法中检索错误消息。我使用的是Visual Studio 2013 Update 4,版本是MVC 5 return BadRequest("Error! Error adding the device"); 请帮忙。提前谢谢。经过研究,我找到了解决办法。因为这

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

return BadRequest("Error!  Error adding the device");

请帮忙。提前谢谢。

经过研究,我找到了解决办法。因为这是一种Web API方法,所以我通过我的网站调用了它。我像下面这样调用它,
RequestUrl
是这个webapi方法的url。如果方法中有参数,我们必须将其写入querystring

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();
我们还可以使用以下代码获得响应类型

Response.ReasonPhrase

这样我就可以得到
BadRequest
以及
Ok
的消息。宾果

自定义错误页也可能导致您的邮件无法显示。如果您的web.config文件包含以下内容,请尝试将其删除,因为它将拦截您的400个状态错误:如果您确实将
existingResponse=“Replace
更改为
existingResponse=“PassThrough

<httpErrors existingResponse="Replace" errorMode="Custom">
  <remove statusCode="404" subStatusCode="-1"/>
  <error statusCode="404" prefixLanguageFilePath="" path="/myapppath/error404.aspx" responseMode="ExecuteURL"/>
</httpErrors


您必须设置ReasonPhase和wrap ResponseMessage以获得IHttpActionResult:

return this.ResponseMessage(new HttpResponseMessage
        {
          StatusCode = HttpStatusCode.BadRequest,
          ReasonPhrase = ex.Message
        });

您能更具体地描述一下您的解决方案是如何工作的吗?我们是否仍然返回BadRequest(“错误!添加设备时出错”);