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

ASP.NET Web API连接字符串VS可用,IIS部署后未初始化异常排查

解决ASP.NET Web API发布到IIS 10.0后连接字符串未初始化异常

问题场景

发布ASP.NET Web API到IIS 10.0后,出现异常:The ConnectionString property has not been initialized。
读取连接字符串的代码:

string sqlDataSource = _configuration.GetConnectionString("Test_Server");

web.config配置:

<connectionStrings>
    <remove name="LocalSqlServer" />
    <add name="Test_Server"
         connectionString="Server=ServerName;Database=DBName;User ID=myname;Password=mypassword"  />
</connectionStrings>

已在IIS中配置对应连接字符串。

排查与解决步骤

  • 检查IIS连接字符串配置一致性
    IIS站点级别的连接字符串会覆盖web.config配置,需确认:

    • IIS中配置的连接字符串名称完全匹配Test_Server(注意大小写敏感)
    • 连接字符串内容完整,无Server、Database等关键参数遗漏
  • 确认配置读取方式适配项目类型

    • 若为ASP.NET Core Web API:确保_configuration已正确注入,且Program.cs中配置源包含web.config:
      var builder = WebApplication.CreateBuilder(args);
      // 确保加载web.config作为配置源
      builder.Configuration.AddXmlFile("web.config", optional: true, reloadOnChange: true);
      
    • 若为传统ASP.NET Web API:需改用ConfigurationManager读取,而非_configuration.GetConnectionString:
      string sqlDataSource = ConfigurationManager.ConnectionStrings["Test_Server"].ConnectionString;
      
  • 验证发布后的web.config完整性
    进入IIS站点对应的物理目录,检查实际生成的web.config是否包含<connectionStrings>节点,确认发布过程未覆盖或丢失该配置;同时检查Web.Release.config等配置转换文件,确保未移除/修改Test_Server连接字符串。

  • 调试验证连接字符串读取结果
    在代码中添加输出,确认读取到的连接字符串是否为null/空:

    string sqlDataSource = _configuration.GetConnectionString("Test_Server");
    // 输出到日志或控制台
    Console.WriteLine($"读取到的连接字符串:{sqlDataSource ?? "null"}");
    

    若为Core项目,可在Program.cs中打印所有配置项,确认连接字符串是否被正确加载。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:02:03