使用 HttpRequestException 获取失败请求的响应正文

Getting response body on failed request with HttpRequestException

我正在尝试记录来自 HttpRequestException 的失败请求。

我的服务器 returns 错误代码 在响应正文中附加 JSON 负载。我需要访问那个 JSON。如果请求出错,我该如何读取响应正文?我知道实际响应不为空。这是一个 API,我确认它 returns JSON 有效载荷带有 4xx 状态代码,提供了有关错误的详细信息。

如何访问它?这是我的代码:

using (var httpClient = new HttpClient())
{
    try
    {
        string resultString = await httpClient.GetStringAsync(endpoint);
        var result = JsonConvert.DeserializeObject<...>(resultString);
        return result;
    }
    catch (HttpRequestException ex)
    {
        throw ex;
    }
}

我正在尝试获取 throw ex 行中的数据,但找不到方法。

基本上是@RyanGunn 发布但在您的代码中实现的内容。

您应该能够 ReadAsStringAsyncresultString.Content

我正在开发一个使用类似代码的 SDK,除了我们使用 switch 语句来检查我们打算在 DeserializeObject 行之前 return 的各种 HttpStatusCodes

using (var httpClient = new HttpClient())
{
    try
    {
        string resultString = await httpClient.GetStringAsync(endpoint);
        var result = JsonConvert.DeserializeObject<...>(resultString.Content.ReadAsStringAsync().Result);
        return result;
    }
    catch (HttpRequestException ex)
    {
        throw ex;
    }
}

使用 GetAsync 而不是 GetStringAsyncGetAsync 不会抛出异常,并允许您访问响应内容、状态代码和您可能需要的任何其他 header。

查看此 page 了解更多信息。

正如@Frédéric 建议的那样,如果您使用 GetAsync 方法,您将获得正确的 HttpResponseMessage 对象,该对象提供有关响应的更多信息。要在发生错误时获取详细信息,您可以将错误取消标记为 Exception 或响应内容中的自定义异常对象,如下所示:

public static Exception CreateExceptionFromResponseErrors(HttpResponseMessage response)
{
    var httpErrorObject = response.Content.ReadAsStringAsync().Result;

    // Create an anonymous object to use as the template for deserialization:
    var anonymousErrorObject =
        new { message = "", ModelState = new Dictionary<string, string[]>() };

    // Deserialize:
    var deserializedErrorObject =
        JsonConvert.DeserializeAnonymousType(httpErrorObject, anonymousErrorObject);

    // Now wrap into an exception which best fullfills the needs of your application:
    var ex = new Exception();

    // Sometimes, there may be Model Errors:
    if (deserializedErrorObject.ModelState != null)
    {
        var errors =
            deserializedErrorObject.ModelState
                                    .Select(kvp => string.Join(". ", kvp.Value));
        for (int i = 0; i < errors.Count(); i++)
        {
            // Wrap the errors up into the base Exception.Data Dictionary:
            ex.Data.Add(i, errors.ElementAt(i));
        }
    }
    // Othertimes, there may not be Model Errors:
    else
    {
        var error =
            JsonConvert.DeserializeObject<Dictionary<string, string>>(httpErrorObject);
        foreach (var kvp in error)
        {
            // Wrap the errors up into the base Exception.Data Dictionary:
            ex.Data.Add(kvp.Key, kvp.Value);
        }
    }
    return ex;
}

用法:

        using (var client = new HttpClient())
        {
            var response =
                await client.GetAsync("http://localhost:51137/api/Account/Register");


            if (!response.IsSuccessStatusCode)
            {
                // Unwrap the response and throw as an Api Exception:
                var ex = CreateExceptionFromResponseErrors(response);
                throw ex;
            }
        }

source 文章详细介绍了如何处理 HttpResponseMessage 及其内容。