ASP.NET Core中的http客户端异常处理

2024-01-01

我正在使用.net 5最新的prview..下面是mvc中http客户端的代码

var response = await _httpClient.SendAsync(request);
         try
        { 
            response.EnsureSuccessStatusCode();
            data = await response.Content.ReadFromJsonAsync<Abc>();
            return data;
        }
        catch (HttpRequestException ex) when (ex.StatusCode = 404)  ----how to check 404 error?
        {
            throw;
        }
        catch (HttpRequestException ex) when (ex.StatusCode == 503)
        {
            throw;
        }

如何检查 catch.am 中的 404 错误或其他详细信息出现以下错误。提前致谢...


最简单的方法是使用正确的枚举进行比较:

var response = await _httpClient.SendAsync(request);
try
{ 
    response.EnsureSuccessStatusCode();
    data = await response.Content.ReadFromJsonAsync<Abc>();
    return data;
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)  ----how to check 404 error?
{
    throw;
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.ServiceUnavailable)
{
    throw;
}

另一种选择是转换为 (int?),但使用枚举应该提供更好的可读性。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET Core中的http客户端异常处理 的相关文章

随机推荐