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

Can Poyrazoglu

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

我的服务器在响应正文中返回错误代码其他JSON负载。我需要访问该JSON。如果请求错误,我如何读取响应正文?我知道实际的回应不是null。这是一个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,但是找不到方法。

仇杀

就像@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;
            }
        }

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

当Java中的请求失败时,如何获取http响应正文?

如何使用Retrofit-Android记录请求和响应正文?

如何使用瓶子获取请求正文?

OkHttp-获取失败的响应正文

真的没有办法从失败的js提取请求中获取响应正文吗?

使用Retrofit 2.0 POST方法获取请求正文内容

Robot Framework-Ride:发布请求无法获取响应正文

在正文中获取原始请求以及正文

在使用JAVA的Azure函数中,如何获取请求正文

使用JSON正文发送POST请求时出现400响应

使用硒和代理获取请求正文

从卷曲请求获取状态代码和响应正文

TypeError:网络请求使用获取ReactNative和Laravel响应失败

如何使用Wiremock在响应中返回字段中的请求正文

使用file_get_contents获取失败时的响应正文

空响应正文与ajax请求

AFNetworking 2-请求失败时无响应正文

使用Http-request在单个请求中获取响应代码和响应正文

改进:请求失败时获取原始响应正文

请求失败时从AlamoFire获取JSON响应

如何使用 sinon.fakeServer 响应请求正文?

如何使用 httptools 从请求中获取正文?

无法通过使用 Postman 发送数据的 resify 获取请求正文

如何使用Wiremock中的响应模板使用来自请求的数据设置响应正文值?

使用@Body 改造 POST 请求返回空响应正文

即使 OAuth2 验证失败,如何记录 http 请求/响应正文?

如何在java中获取失败的HTTP请求正文?

使用 Cypress,如何获取由非请求事件触发的 api 调用的响应正文

React Async/Await 使用请求正文获取数据