您可以使用以下代码读取HttpWebResponse异常中的json的body:

try
{
    // 发送 HTTP 请求并获取响应
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/api");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // 读取响应内容
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        string json = reader.ReadToEnd();
        // 处理响应内容
    }
}
catch (WebException ex)
{
    // 读取响应内容
    using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
    {
        string json = reader.ReadToEnd();
        // 处理响应内容
    }
}

在上面的代码中,我们使用try-catch语句来捕获HttpWebRequest的异常,然后使用StreamReader读取异常响应中的json内容。注意,在捕获异常时,我们使用WebException的Response属性来获取异常响应。

c#的webapi且net451 怎么读取HttpWebResponse异常中的json的body

原文地址: http://www.cveoy.top/t/topic/XYk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录