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

.NET Framework 4.8调用OpenAI API失败问题求助(含VSTO场景)

.NET 4.8 VSTO插件调用OpenAI API异常排查与解决

问题概述

代码在.NET 8环境下调用OpenAI API正常,但迁移到.NET 4.8后出现异常:

  • 最初执行await client.PostAsync时无响应无报错,修正异步等待逻辑后,抛出无法创建SSL/TLS安全通道的异常
  • 相同代码在.NET 4.8控制台应用中可正常运行,但在.NET 4.8 VSTO插件中触发错误
  • 已尝试网上常见的注册表修改方案,无效果

相关代码示例

private static async Task Request()
{
    string Result;
    string APIK_KEY = "some api key";
    string someLongText = @"long text";

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", APIK_KEY);

    var request = new OpenAIRequest
    {
        Model = "gpt-3.5-turbo",
        Temperature = 0.7f,
        MaxTokens = 200,
        Messages = new List<Message>()
        {
            new Message() { Role = "system", Content = "You are a helpful assistant." },
            new Message() { Role = "user", Content = "Please concise below text: " + someLongText }
        }
    };
    // .NET 8使用JsonSerializer.Serialize,.NET 4.8用自定义Serialize类
    var json = Serialize.SerializeJson<OpenAIRequest>(request);   
    var content = new StringContent(json, Encoding.UTF8, "application/json");

    HttpResponseMessage response = null;
    try
    {
        response = await client.PostAsync("https://api.openai.com/v1/chat/completions", content);
    }
    catch (Exception e)
    {
        throw e;
    }
    var resjson = await response.Content.ReadAsStringAsync();

    if (!response.IsSuccessStatusCode)
    {
        var errorResponse = Serialize.DeserializeJson<OpenAIErrorResponse>(resjson);
        throw new System.Exception(errorResponse.Error.Message);
    }
    var data = Serialize.DeserializeJson<Root>(resjson);
    Result = data.Choices[0].Message.Content;

    Console.WriteLine(Result);
    Console.ReadLine();
    return;
}

错误详情

System.Net.Http.HttpRequestException
  HResult=0x80131500
  Message=An error occurred while sending the request.
  Source=mscorlib
  StackTrace:
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at A_Add_in.OpenAIServices.<SendPrompt>d__9.MoveNext() in C[...]:line 151
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at A_Add_in.Models.OpenAIModel.<GetAIResponse>d__4.MoveNext() in C[...]:line 31

Inner Exception 1:
WebException: The request was aborted: Could not create SSL/TLS secure channel.

解决方案

1. 强制指定TLS版本

VSTO插件运行在Office进程中,默认SSL/TLS协议可能未启用TLS1.2/TLS1.3,在HttpClient初始化前添加:

// 显式启用TLS1.2和TLS1.3,禁用旧协议避免冲突
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
ServicePointManager.SecurityProtocol &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11);

2. 替换为Json.NET处理序列化

.NET 4.8中System.Text.Json兼容性不如Newtonsoft.Json,替换自定义序列化逻辑:

  • 安装Newtonsoft.Json NuGet包
  • 修改序列化代码:
    var json = JsonConvert.SerializeObject(request);
    // 反序列化错误响应
    var errorResponse = JsonConvert.DeserializeObject<OpenAIErrorResponse>(resjson);
    // 反序列化返回结果
    var data = JsonConvert.DeserializeObject<Root>(resjson);
    

3. 优化HttpClient生命周期

避免每次请求新建HttpClient,使用静态单例减少连接问题:

private static readonly HttpClient _client = new HttpClient();

static YourPluginClass()
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
    _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_api_key");
}

4. 检查Office进程权限

  • 尝试以管理员身份运行Office,确认是否是权限限制导致SSL通道创建失败
  • 检查Office信任中心设置,确保插件被允许访问网络

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:20:06