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

ASP.NET Core 2.0获取连接字符串遇ArgumentNullException的解决方法

解决ASP.NET Core 2.0中获取连接字符串时的ArgumentNullException问题

嘿,这个问题我之前也踩过坑!你遇到的ArgumentNullException: 值不能为空。参数名称: connectionString,根源是你的appsettings.json配置结构出错了——你把ConnectionStrings节点嵌套到Logging节点里面了,ASP.NET Core的配置系统只会在根节点下找ConnectionStrings,所以Configuration.GetConnectionString("UserDatabase")根本读不到值,返回了null,自然就触发异常了。

具体修复步骤

1. 修正appsettings.json的结构

把ConnectionStrings移到根节点,和Logging同级,修改后的配置文件应该是这样的:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "ConnectionStrings": {
    "UserDatabase": "Server=DESKTOP-FSES7UK;Database=xxx;User Id=sa; Password=xxxxxxx;Trusted_Connection=True;"
  }
}

2. (可选)验证连接字符串是否正确读取

如果你想确认修复后能读到值,可以在ConfigureServices方法里加个调试输出(仅限开发环境):
首先,记得给ConfigureServices方法加上IHostingEnvironment参数:

public void ConfigureServices(IServiceCollection services, IHostingEnvironment env)

然后添加调试代码:

// 先获取连接字符串
var connString = Configuration.GetConnectionString("UserDatabase");
// 开发环境下输出到控制台,确认是否拿到值
if (env.IsDevelopment())
{
    Console.WriteLine($"已读取到连接字符串:{connString}");
}
// 再配置DbContext
services.AddDbContext<fooContext>(options => options.UseSqlServer(connString));

额外小知识

ASP.NET Core里的Configuration.GetConnectionString("xxx")其实是个快捷方法,它等价于Configuration["ConnectionStrings:xxx"],所以只要ConnectionStrings在根节点,这个方法就能正确定位到你的连接字符串配置项啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:03:53