使用HttpRequestException

时间:2016-02-23 21:08:38

标签: c# .net httpclient

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

我的服务器在响应正文中返回错误代码其他JSON有效内容。我需要访问那个JSON。如果出现错误请求,如何阅读响应正文?我知道实际的响应不是空的。这是一个API,我确认它返回带有4xx状态代码的JSON有效负载,详细了解错误。

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

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行中获取数据,但我找不到方法。

3 个答案:

答案 0 :(得分:8)

正如@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及其内容的更多信息。

答案 1 :(得分:1)

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

您应该能够ReadAsStringAsync

resultString.Content

我正在使用类似代码的SDK,除了我们使用switch语句检查我们打算在HttpStatusCodes行之前返回的各种DeserializeObject

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;
    }
}

答案 2 :(得分:0)

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

有关详情,请参阅此page