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

ASP.NET Core运行报Value cannot be null (Parameter 'Password')错误求助

问题根因

你遇到的System.ArgumentNullException: 'Value cannot be null. (Parameter 'Password')'报错,根因是代码执行Password = Configuration.GetValue<string>("SQL_PASSWORD")时,从配置系统读取到的SQL_PASSWORD值为null,赋值给SqlConnectionStringBuilder的Password属性时触发了参数非空校验。另外你的代码还依赖DefaultConnection连接字符串配置,你提供的appsettings.json中同样没有该配置项。

修复方案
    1. 补充appsettings.json配置
      在你的appsettings.json中添加缺失的ConnectionStrings节点和SQL_PASSWORD节点,参考示例:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=你的数据库地址;Database=你的数据库名称;User ID=你的数据库用户名;TrustServerCertificate=True;"
  },
  "SQL_PASSWORD": "你的数据库登录密码"
}
    1. 敏感配置安全存储(可选但推荐)
      本地开发时不要把密码明文写在appsettings.json里,可以用ASP.NET Core机密管理器存储敏感信息:右键你的项目 → 选择「管理用户机密」,在弹出的secrets.json中添加"SQL_PASSWORD": "你的数据库登录密码"即可。生产环境建议用环境变量、云配置中心等方式传递敏感配置,避免硬编码泄露。
    1. 配置空校验兜底(可选)
      可以在代码中增加配置空校验,提前抛出清晰的错误提示,避免触发底层框架的通用参数空异常:
string GetSqlConnectionString()
{
    var baseConnStr = Configuration.GetConnectionString("DefaultConnection");
    if (string.IsNullOrWhiteSpace(baseConnStr))
    {
        throw new InvalidOperationException("缺少DefaultConnection连接字符串配置,请检查配置文件或环境变量");
    }
    var sqlPassword = Configuration.GetValue<string>("SQL_PASSWORD");
    if (string.IsNullOrWhiteSpace(sqlPassword))
    {
        throw new InvalidOperationException("缺少SQL_PASSWORD数据库密码配置,请检查配置文件或环境变量");
    }
    var connStr = new SqlConnectionStringBuilder(baseConnStr)
    {
        Password = sqlPassword,
        Authentication = SqlAuthenticationMethod.SqlPassword,
    };
    return connStr.ToString();
}
    1. 环境配置检查
      如果是容器部署、CI/CD流水线发布的场景,需要检查对应环境的环境变量是否已经正确配置ConnectionStrings__DefaultConnection和SQL_PASSWORD,ASP.NET Core配置系统会优先读取环境变量中的配置值,优先级高于appsettings.json。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:27:05