You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET调用RestAPI始终进入catch块,无法获取响应求助

问题排查与修复方案

你的代码始终进入catch块却无法定位具体原因,核心问题在于无参catch没有捕获异常详情,先把这一步补上,再针对常见问题逐一修复:

第一步:捕获异常详情(定位问题关键)

修改catch块,输出完整异常信息,这样才能知道到底哪里出错:

catch (Exception ex)
{
    latestVersion = "Not succeeded";
    Output.WriteLine($"RESULT: {latestVersion}");
    Output.WriteLine($"错误详情: {ex.Message}");
    if (ex.InnerException != null)
    {
        Output.WriteLine($"内部错误: {ex.InnerException.Message}");
    }
    Report.TestStepFail(testStepIdentifier, testStepDescription);
}

常见问题与对应修复

1. 编码错误导致身份验证失败

你用Encoding.Default编码用户名密码,这会依赖系统默认编码,可能导致Base64结果不正确,替换为标准的UTF8编码:

request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("user:12345"));

2. TLS版本不兼容

现代API大多要求TLS 1.2及以上版本,HttpWebRequest默认可能使用旧版本,在创建请求前强制设置:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;

3. 不必要的请求头设置

GET请求没有请求体,不需要设置Content-Type,移除这行代码:

// request.ContentType = "application/json"; // 直接删除

4. 资源未正确释放

你的代码没有用using语句管理WebResponse、Stream等资源,可能引发异常或资源泄漏,修改try块内的代码:

try
{
    using (WebResponse webResponse = request.GetResponse())
    using (Stream webStream = webResponse.GetResponseStream())
    using (StreamReader responseReader = new StreamReader(webStream))
    {
        latestVersion = responseReader.ReadToEnd();
        Output.WriteLine("RESULT = " + latestVersion);
        Report.TestStepPass(testStepIdentifier, testStepDescription);
    }
}

完整修改后的代码

public class MyClass {
  
  public static void CreateObject() {
    string latestVersion;
    string testStepDescription = "API_TEST: ";
    string testStepIdentifier = "TestStep";

    // 强制设置TLS版本
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;

    string uri = "https://MyAPI.Test/endpoint";
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "GET";
    // 使用UTF8编码生成Basic认证串
    request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("user:12345"));

    try {
      using (WebResponse webResponse = request.GetResponse())
      using (Stream webStream = webResponse.GetResponseStream())
      using (StreamReader responseReader = new StreamReader(webStream))
      {
        latestVersion = responseReader.ReadToEnd();
        Output.WriteLine("RESULT = "+ latestVersion);
        Report.TestStepPass(testStepIdentifier, testStepDescription);
      }
    }
    catch (Exception ex) {
      latestVersion = "Not succeeded";
      Output.WriteLine("RESULT "+ latestVersion);
      Output.WriteLine($"错误信息: {ex.Message}");
      if (ex.InnerException != null)
      {
          Output.WriteLine($"内部错误: {ex.InnerException.Message}");
      }
      Output.WriteLine("RESULT = Nooooo");
      Report.TestStepFail(testStepIdentifier, testStepDescription);
    }
  }
}

先运行修改后的代码,通过catch块输出的错误信息,就能精准定位问题(比如身份验证失败、端点不存在、网络连通性问题等)。

内容的提问来源于stack exchange,提问作者Andreas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:51:39