如何在C# HttpClient请求中记录HTTP响应状态码?
记录HttpClient请求的HTTP响应状态码实现方案
要记录HTTP响应的状态码(如200、201、400),只需通过HttpResponseMessage对象的StatusCode属性获取状态码,再结合业务需求做日志输出或后续处理即可。以下是修改后的完整代码:
public async void Main() { String filepath = Dts.Variables["User::FileName"].Value.ToString(); if (File.Exists(filepath)) { try { // 读取JSON文件 string jsonData = File.ReadAllText(filepath); using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://your-url.com"); // 改用异步调用避免阻塞,更符合HttpClient最佳实践 var response = await client.PostAsync("/url-path", new StringContent(jsonData, Encoding.UTF8, "application/json")); // 获取状态码的数字值和枚举名称 int statusCodeNumber = (int)response.StatusCode; string statusCodeName = response.StatusCode.ToString(); // 基础状态码记录 Console.WriteLine($"HTTP响应状态码: {statusCodeNumber} ({statusCodeName})"); // 按状态码类型分支处理 if (response.IsSuccessStatusCode) { Console.WriteLine("请求处理成功"); var responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine("响应内容: " + responseContent); } else { Console.WriteLine("请求处理失败"); // 针对常见错误码做单独提示 switch (statusCodeNumber) { case 400: Console.WriteLine("错误提示: 请求参数格式不正确或缺失必填项"); break; case 401: Console.WriteLine("错误提示: 未授权访问,请检查认证信息"); break; case 500: Console.WriteLine("错误提示: 服务器内部异常"); break; // 可根据需要扩展更多状态码分支 } // 读取错误响应内容便于排查 var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine("错误详情: " + errorContent); } } } catch (Exception ex) { Console.WriteLine($"请求过程出错: {ex.Message}"); } } else { Console.WriteLine("指定路径下的JSON文件不存在"); } }
关键要点说明:
- 状态码获取:通过
(int)response.StatusCode拿到数字形式的状态码,response.StatusCode.ToString()获取枚举名称(如"OK"对应200) - 异步优化:将原代码的
.Result改为await异步调用,避免主线程阻塞,符合HttpClient的最佳使用方式 - 分支处理:
- 用
response.IsSuccessStatusCode快速判断2xx类成功状态 - 通过switch分支对400、401等常见错误码做针对性提示
- 读取响应/错误内容辅助问题排查
- 用
内容的提问来源于stack exchange,提问作者Beanymattd
相关产品推荐
相关产品推荐

