C#中GetFromJsonAsync与ReadAsStringAsync遇404挂起的解决咨询
解决HttpClient请求404时挂起及触发异常的问题
问题说明
在C#中使用HttpClient的GetFromJsonAsync和ReadAsStringAsync方法时,请求返回404状态码的URL,程序不会抛出异常而是直接挂起,测试函数执行时会卡在请求步骤。需要实现响应不符合预期时触发异常或给出提示。
测试代码如下:
private static HttpClient apiClient = new HttpClient() { BaseAddress = new Uri ("https://httpbin.org/") }; public static async Task TestRequest() { using HttpResponseMessage response = await apiClient.GetAsync("/bad/path"); response.EnsureSuccessStatusCode(); var jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine($"{jsonResponse}"); }
解决方案
1. 确保正确异步等待任务执行
程序挂起大概率是因为调用TestRequest时未使用await,而是用了Wait()或Result导致死锁。必须在异步上下文里通过await调用:
public static async Task Main(string[] args) { await TestRequest(); }
2. 利用EnsureSuccessStatusCode触发异常
response.EnsureSuccessStatusCode()本身会在响应状态码不在200-299范围内时抛出HttpRequestException,只需添加异常捕获即可处理:
public static async Task TestRequest() { using HttpResponseMessage response = await apiClient.GetAsync("/bad/path"); try { response.EnsureSuccessStatusCode(); // 非2xx状态码直接抛出异常 } catch (HttpRequestException ex) { Console.WriteLine($"请求失败:{ex.Message}"); throw; // 可选:重新抛出异常让上层逻辑处理 } var jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); }
3. 手动判断状态码实现自定义提示
如果不想抛出异常,也可以手动判断状态码并给出提示:
public static async Task TestRequest() { using HttpResponseMessage response = await apiClient.GetAsync("/bad/path"); if (!response.IsSuccessStatusCode) { Console.WriteLine($"请求失败,状态码:{response.StatusCode}"); return; // 终止后续逻辑或执行其他处理 } var jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); }
4. 设置HttpClient超时避免无限挂起
为HttpClient添加超时配置,防止因网络问题导致程序无限等待:
private static HttpClient apiClient = new HttpClient() { BaseAddress = new Uri("https://httpbin.org/"), Timeout = TimeSpan.FromSeconds(10) // 设置10秒超时 };
内容的提问来源于stack exchange,提问作者roux
相关产品推荐
相关产品推荐

