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

Can*_*ğlu 7 .net c# 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图获得数据throw ex,但我找不到方法.

ven*_*mit 10

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

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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

        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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

这是文章,详细介绍了有关处理HttpResponseMessage及其内容的更多信息.