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

.NET 4.7.2控制台调用Azure Form Recognizer API后意外关闭无报错

排查Azure Form Recognizer AnalyzeDocumentFromUriAsync 导致控制台意外退出的问题

1. 补全异步方法的等待与错误捕获

.NET 4.7.2的控制台同步Main方法直接调用异步操作时,主线程会提前退出,导致程序无提示关闭。必须确保阻塞主线程等待异步完成,并添加完整的异常捕获:

static void Main(string[] args)
{
    try
    {
        // 阻塞主线程等待异步操作执行完毕
        AnalyzeInvoiceAsync().Wait();
    }
    catch (AggregateException ex)
    {
        // 展开聚合异常获取真实错误信息
        foreach (var innerEx in ex.InnerExceptions)
        {
            Console.WriteLine($"错误详情: {innerEx.Message}");
            Console.WriteLine($"堆栈跟踪: {innerEx.StackTrace}");
        }
    }
    Console.ReadLine(); // 防止执行完成后直接关闭控制台
}

private static async Task AnalyzeInvoiceAsync()
{
    var endpoint = "你的Endpoint";
    var apiKey = "你的密钥";
    var client = new DocumentAnalysisClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
    
    var documentUri = new Uri("你的PDF文件URI");
    var operation = await client.AnalyzeDocumentFromUriAsync(WaitUntil.Completed, "prebuilt-invoice", documentUri);
    
    // 示例:输出提取的发票编号
    var invoiceId = operation.Value.Fields["InvoiceId"]?.ValueString;
    Console.WriteLine($"提取到的发票编号: {invoiceId}");
}

2. 验证SDK版本兼容性

确认你安装的Azure.AI.FormRecognizer NuGet包版本支持.NET 4.7.2。部分高版本SDK可能对框架版本有更高要求,建议降级到兼容的稳定版本(如4.1.0版本)。

3. 检查网络与权限配置

  • 测试控制台环境能否正常访问你的Form Recognizer Endpoint,可通过浏览器直接访问Endpoint地址验证连通性
  • 在Azure门户的IAM页面,确认你的API密钥对应的账号拥有Cognitive Services User或足够的接口调用权限

4. 排查PDF文件有效性

即使URI正常,也要确认PDF文件符合Form Recognizer的要求:

  • 文件大小不超过50MB
  • 页数不超过200页
  • 文件未加密、未损坏,可正常打开读取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:02:02