.NET 6通过Docker连接SQL Server时出现User ID为空异常
异常信息
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

