【问题标题】:400 Bad Request | Receive custom error message or model from ASP.NET Web API400 错误请求 |从 ASP.NET Web API 接收自定义错误消息或模型
【发布时间】:2019-11-27 05:01:09
【问题描述】:

我们有一个由第三方公开的 Web API,我们没有任何控制权。看起来他们正在将自定义错误消息模型包装在退回 400(Bad Request)上。

我们在使用 Postman 时得到自定义错误消息模型

{
    "Message": "Site Name Exists",
    "ErrorId": "<some-guid>",
    "ErrorCode": 400,
    "GeneratedTime": "<some-datatime>",
    "RequestedUri": "origin-api-uri"
} 

我们尝试使用 HttpWebResponseWebResponse 从 API 获取响应,但它会在 httpWebRequest.GetResponse() 上引发 400 代码异常。它没有给我们在 Postman 中得到的预期响应,但它显示 400 (Bad Request) 并带有默认错误消息,“远程服务器返回错误”。

我们希望以 Postman 的身份获取原始错误消息。 有什么想法吗?

【问题讨论】:

    标签: c# asp.net-web-api httpwebrequest httpwebresponse


    【解决方案1】:

    默认情况下,大多数异常都会被转换为状态码为 500、内部服务器错误或 400 错误请求的 HTTP 响应,这是非常痛苦的情况。您需要在 catch 块中捕获 WebException。

    参考:Exception Handling in ASP.NET Web API

    试一试。

     catch (WebException ex)
            {
                StreamReader sr = new StreamReader(ex.Response.GetResponseStream());
                Console.WriteLine(sr.ReadToEnd());
            }
    

    【讨论】:

    • 我们错过了..GetResponseStream()。感谢您的回答!
    猜你喜欢
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2019-06-21
    • 2014-04-05
    • 1970-01-01
    • 2011-03-09
    相关资源
    最近更新 更多