【问题标题】:Unable getting the Error Message of BadRequest in Web Api 2无法在 Web Api 2 中获取 BadRequest 的错误消息
【发布时间】:2015-03-18 08:10:51
【问题描述】:

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

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

请帮忙。提前致谢。

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api asp.net-mvc-5


    【解决方案1】:

    经过研究和研究,我找到了解决方案。由于这是 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();
    

    我们也可以使用下面的代码来获取响应类型。

    Response.ReasonPhrase
    

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

    【讨论】:

    • 您能否更具体地描述一下您的解决方案是如何工作的,我们是否仍然返回 BadRequest("Error! Error 添加设备")​​;
    【解决方案2】:

    自定义错误页面也可能导致您的消息不显示。如果您的 web.config 文件具有以下内容,请尝试将其删除,因为它会拦截您的 400 状态错误:如果您确实有以下更改 existingResponse="ReplaceexistingResponse="PassThrough

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

    【讨论】:

      【解决方案3】:

      您必须设置 ReasonPhrase 并包装 ResponseMessage 以获得 IHttpActionResult:

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

      【讨论】:

        猜你喜欢
        • 2016-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-10
        • 2020-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多