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

ASP.NET Core 6.0读取连接字符串遇空值错误求助

连接字符串为null的问题排查与解决

问题概述

尝试从appsettings.json获取连接字符串并在Startup.cs中使用时,持续收到错误:Value cannot be null. Parameter name: connectionString。

相关配置与代码

appsettings.json:

{
  "Project": {
    "ConnectionStrings": "Data Source=(local)\\SQLSERVER; Database=RecommendationSite; Persist Security Info=false; User ID='sa'; Password='sa'; MultipleActiveResultSets=True; Trusted_Connection=False;",
    "CompanyName": "RecommendationSite1 ",
    "CompanyPhone": "+7 (111) 111-11-11",
    "CompanyPhoneShort": "+71111111111",
    "CompanyEmail": "contact@recommendationsite.com"
  }
}

Startup.cs核心代码:

public void ConfigureServices(IServiceCollection services)
{
    Configuration.Bind("Project", new Config());

    // ...其他服务注册

    services.AddDbContext<AppDbContext>(x => x.UseSqlServer(Config.ConnectionString));

    // ...身份认证配置

    services.AddDbContext<RecommendationSiteContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("RecommendationSiteContext")));
}

错误原因分析

  1. Config类绑定逻辑错误

    • Configuration.Bind("Project", new Config());仅创建了一个临时的Config实例,没有将绑定后的配置值赋值给静态的Config.ConnectionString属性,导致该静态属性始终为null。
    • 可能存在属性名称不匹配:appsettings中键为ConnectionStrings(复数),但Config类中对应的属性是ConnectionString(单数),绑定无法匹配,值无法被赋值。
  2. RecommendationSiteContext连接字符串获取方式错误

    • Configuration.GetConnectionString("RecommendationSiteContext")默认读取配置中顶级ConnectionStrings节点下的子项,但你的配置中不存在这个结构,连接字符串实际在Project节点下,因此该调用返回null。

修复步骤

步骤1:统一配置属性名称

确保Config类的属性名称与appsettings中的键完全一致。例如:

public class Config
{
    public static string ConnectionStrings { get; set; } // 与appsettings中的"ConnectionStrings"匹配
    public string CompanyName { get; set; }
    // 其他属性...
}

如果希望保持Config属性为ConnectionString,则修改appsettings中的键为ConnectionString(单数)。

步骤2:正确绑定并赋值静态属性

替换原来的绑定代码,将配置值赋值给静态属性:

var configInstance = new Config();
Configuration.Bind("Project", configInstance);
Config.ConnectionStrings = configInstance.ConnectionStrings;

步骤3:修复RecommendationSiteContext的连接字符串读取

将获取连接字符串的代码改为直接读取Project节点下的值,或复用Config的静态属性:

// 方式1:直接读取配置路径
services.AddDbContext<RecommendationSiteContext>(options =>
        options.UseSqlServer(Configuration["Project:ConnectionStrings"]));

// 方式2:复用Config静态属性
services.AddDbContext<RecommendationSiteContext>(options =>
        options.UseSqlServer(Config.ConnectionStrings));

额外验证

确保appsettings.json的复制到输出目录设置为「如果较新则复制」或「始终复制」,避免程序运行时无法读取配置文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:25:08