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

.NET 6通过Docker连接SQL Server时出现User ID为空异常

数据库连接ArgumentNullException异常排查与解决

异常信息

2024-03-18 11:50:22 Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'User ID')
2024-03-18 11:50:22 at Microsoft.Data.Common.ADP.CheckArgumentNull(Object value, String parameterName)
2024-03-18 11:50:22 at Microsoft.Data.SqlClient.SqlConnectionStringBuilder.SetValue(String keyword, String value)
2024-03-18 11:50:22 at Microsoft.Data.SqlClient.SqlConnectionStringBuilder.set_UserID(String value)
2024-03-18 11:50:22 at Program.$(String[] args) in Program.cs:line 22

配置文件(appsettings.Development.json)

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "SQLDbConnection": "Server=localhost,1433;Initial Catalog=db;",
  },
  "UserId": "sa",
  "Password": "passw0rd"
}

数据库连接代码(Program.cs)

// Connect to server using connection string from appSettings.Development.json
var sqlConBuilder = new SqlConnectionStringBuilder();

sqlConBuilder.ConnectionString = builder.Configuration.GetConnectionString("SQLDbConnection");

// Use user ID and password directly from configuration
sqlConBuilder.UserID = builder.Configuration["UserId"];
sqlConBuilder.Password = builder.Configuration["Password"];

builder.Services.AddDbContext<AppDbContext>(opt => opt.UseSqlServer(sqlConBuilder.ConnectionString));

异常原因

异常提示User ID参数为null,说明代码中builder.Configuration["UserId"]未读取到配置值。Docker环境下常见原因包括:

  • 未明确加载appsettings.Development.json配置文件
  • 配置文件未被复制到Docker镜像中
  • 运行时环境变量未正确覆盖配置值

解决方法

  • 明确加载开发环境配置:在Program.cs开头添加配置加载代码,确保开发环境配置被读取:

    var builder = WebApplication.CreateBuilder(args);
    // 强制加载开发环境配置文件
    builder.Configuration.AddJsonFile("appsettings.Development.json", optional: false, reloadOnChange: true);
    
  • 确保配置文件被复制到Docker镜像:在Dockerfile中添加复制指令,将配置文件同步到容器内:

    COPY ["appsettings.Development.json", "."]
    
  • 验证环境变量配置:如果通过环境变量传递凭据,确保Docker运行时已设置对应变量,或在docker-compose.yml中配置:

    services:
      api:
        environment:
          - UserId=sa
          - Password=passw0rd
    
  • 临时调试方案:直接在连接字符串中嵌入凭据,验证数据库连接是否正常:

    "ConnectionStrings": {
      "SQLDbConnection": "Server=localhost,1433;Initial Catalog=db;User ID=sa;Password=passw0rd;"
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 23:47:20