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

Azure应用设置中ConnectionStrings获取返回空字符串问题

解决Azure Web应用读取连接字符串返回Null的问题

本地运行正常,发布到Azure后,调用builder.Configuration.GetConnectionString("AppConfig")返回null,导致AddAzureAppConfiguration抛出空连接字符串异常。Azure门户中曾尝试将连接字符串名称设为「AppConfig」和「ConnectionStrings:AppConfig」,均未解决问题,当前截图显示键名为「AppConfig」。

排查与解决步骤:

  • 确认Azure连接字符串类型
    在Azure门户「应用设置」→「连接字符串」中,确保连接字符串的类型选择为Custom。ASP.NET Core的GetConnectionString方法仅会识别类型为对应数据库类型或Custom的连接字符串,类型错误会导致无法读取。

  • 直接通过配置键读取
    跳过GetConnectionString方法,直接通过完整配置键读取:

    // 如果Azure中连接字符串名称为「AppConfig」,实际键为ConnectionStrings:AppConfig
    string issueIdentityAPIConfigConnectionString = builder.Configuration["ConnectionStrings:AppConfig"];
    

    若Azure中未自动添加前缀,直接读取键名:

    string issueIdentityAPIConfigConnectionString = builder.Configuration["AppConfig"];
    
  • 调整配置加载顺序
    WebApplication.CreateBuilder(args)已默认加载环境变量和Azure应用设置,无需额外调用AddEnvironmentVariables(),可移除该语句或调整代码顺序,确保先读取配置再初始化Azure App Configuration:

    var builder = WebApplication.CreateBuilder(args);
    
    // 先读取连接字符串
    string issueIdentityAPIConfigConnectionString = builder.Configuration.GetConnectionString("AppConfig");
    // 再加载Azure App Configuration
    builder.Configuration.AddAzureAppConfiguration(issueIdentityAPIConfigConnectionString);
    
    // 后续服务配置
    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
  • 检查发布配置
    发布到Azure时,确认发布配置的「设置」选项卡中,没有手动设置空的连接字符串值,且启用了从Azure应用服务读取配置的选项,避免发布过程覆盖Azure门户中的配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 12:15:11