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

C#代码控制台运行正常,Word插件调用Azure语言服务失败求助

Word插件调用Azure语言服务API报错问题

我C#开发经验有限,正在开发一款Word插件,功能是选中文档文本后调用Azure语言服务API。这段代码在独立Windows控制台应用中可正常运行:

Debug.WriteLine("beginning of the try");
string azureEndpoint = "https://redacted.cognitiveservices.azure.com/"; // 替换为实际端点URL
string subscriptionKey = "redacted"; // 替换为实际订阅密钥

Uri endpoint = new Uri(azureEndpoint);
AzureKeyCredential credential = new AzureKeyCredential(subscriptionKey);

QuestionAnsweringClient client = new QuestionAnsweringClient(endpoint, credential);

string projectName = "redacted";
string deploymentName = "production";
QuestionAnsweringProject project = new QuestionAnsweringProject(projectName, deploymentName);
Response<AnswersResult> response = client.GetAnswers("Where is your headquarters?", project);

foreach (KnowledgeBaseAnswer answer in response.Value.Answers)
{
    Debug.WriteLine($"({answer.Confidence:P2}) {answer.Answer}");
    Debug.WriteLine($"Source: {answer.Source}");
    Debug.WriteLine($"Confidence:  {answer.Confidence}");
}

但将代码绑定到Word插件按钮点击事件时出现错误(错误码10054:远程主机强制关闭现有连接),尝试改用异步调用后问题依旧,最终报错“重试4次后失败”,插件相关代码如下:

private void button7_Click(object sender, RibbonControlEventArgs e)
{
    var rng = Globals.ThisAddIn.Application.Selection.Range;
    rng.Select();
    var selectedText = rng.Text;

    try
    {
         Debug.WriteLine("beginning of the try");
         string azureEndpoint = "https://redacted.cognitiveservices.azure.com/"; // 替换为实际端点URL
        string subscriptionKey = "redacted"; // 替换为实际订阅密钥

        Uri endpoint = new Uri(azureEndpoint);
        AzureKeyCredential credential = new AzureKeyCredential(subscriptionKey);

        QuestionAnsweringClient client = new QuestionAnsweringClient(endpoint, credential);

        string projectName = "redacted";
        string deploymentName = "production";
        QuestionAnsweringProject project = new QuestionAnsweringProject(projectName, deploymentName);
        Response<AnswersResult> response = client.GetAnswers("Where is your headquarters?", project);

        foreach (KnowledgeBaseAnswer answer in response.Value.Answers)
        {
            Debug.WriteLine($"({answer.Confidence:P2}) {answer.Answer}");
            Debug.WriteLine($"Source: {answer.Source}");
            Debug.WriteLine($"Confidence:  {answer.Confidence}");
        }
    }
    catch (Exception ex)
    {
        // 处理异常(如网络错误、无效响应)
        MessageBox.Show("Error calling Azure Language Service API: " + ex.Message );
    }
}

问题排查与解决方法

  • Office网络环境限制
    Office应用可能受组策略或代理配置影响,无法正常连接Azure服务。

    • 检查Word网络权限:依次点击「文件」→「选项」→「信任中心」→「信任中心设置」→「隐私选项」,确认允许Office连接互联网。
    • 手动配置代理(如果环境需要):为客户端指定代理信息,示例代码如下:
      var handler = new HttpClientHandler
      {
          Proxy = new WebProxy("http://你的代理地址:端口"),
          UseProxy = true
      };
      var httpClient = new HttpClient(handler);
      var clientOptions = new QuestionAnsweringClientOptions { HttpClient = httpClient };
      QuestionAnsweringClient client = new QuestionAnsweringClient(endpoint, credential, clientOptions);
      
  • 正确实现异步调用
    Office插件UI线程不能被长时间阻塞,需使用异步API并正确标记事件方法为async void:

    private async void button7_Click(object sender, RibbonControlEventArgs e)
    {
        var rng = Globals.ThisAddIn.Application.Selection.Range;
        var selectedText = rng.Text;
    
        try
        {
            Debug.WriteLine("beginning of the try");
            string azureEndpoint = "https://redacted.cognitiveservices.azure.com/";
            string subscriptionKey = "redacted";
    
            Uri endpoint = new Uri(azureEndpoint);
            AzureKeyCredential credential = new AzureKeyCredential(subscriptionKey);
    
            QuestionAnsweringClient client = new QuestionAnsweringClient(endpoint, credential);
    
            string projectName = "redacted";
            string deploymentName = "production";
            QuestionAnsweringProject project = new QuestionAnsweringProject(projectName, deploymentName);
            // 调用异步版本API
            Response<AnswersResult> response = await client.GetAnswersAsync("Where is your headquarters?", project);
    
            foreach (KnowledgeBaseAnswer answer in response.Value.Answers)
            {
                Debug.WriteLine($"({answer.Confidence:P2}) {answer.Answer}");
                Debug.WriteLine($"Source: {answer.Source}");
                Debug.WriteLine($"Confidence:  {answer.Confidence}");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("调用Azure语言服务API出错: " + ex.Message);
        }
    }
    
  • Azure服务防火墙限制
    登录Azure门户,找到对应的认知服务资源,进入「网络」设置,检查是否允许插件所在机器的IP访问。测试阶段可临时开启“允许从所有网络访问”,生产环境建议限制指定IP范围。

  • 统一NuGet包版本
    确认控制台和插件中使用的Azure.AI.Language.QuestionAnswering NuGet包版本一致,优先使用最新稳定版,避免版本差异导致的兼容性问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 00:05:58