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

ASP.NET Core 2.0数据库优先模式下connectionString为空异常求助

ArgumentNullException: Value cannot be null. Parameter name: connectionString in ASP.NET Core 2.0 Database-First Approach

Looks like the root cause of your issue is a typo in your configuration file—let's fix that first:

Problem 1: Incorrect Configuration Node Name

Your appsettings.json uses ConnectionString (singular) as the parent node for your connection string, but ASP.NET Core's Configuration.GetConnectionString() method expects the parent node to be ConnectionStrings (plural, with an "s").

When you call Configuration.GetConnectionString("DefaultConnection"), it's designed to look for a structure like this:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=Videos;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Since your current config uses the singular node name, the method returns null, which triggers the ArgumentNullException when passed to UseSqlServer().

Additional Checks to Ensure Everything Works

  1. Verify Configuration File Copy Settings

    • Right-click your appsettings.json file in Visual Studio → Properties
    • Set "Copy to Output Directory" to "Copy if newer" or "Copy always"
    • This ensures the config file is available at runtime, so the app can read the connection string properly.
  2. Confirm Default Configuration Loading
    Your Main method uses WebHost.CreateDefaultBuilder(args), which in ASP.NET Core 2.0 automatically loads appsettings.json and environment-specific config files—so that part of your code is correct. No changes needed here.

Corrected Startup Code (No Changes Needed, But For Context)

Just to confirm, your ConfigureServices method is written correctly once the config is fixed:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    // This will now find the connection string correctly after fixing appsettings.json
    services.AddDbContext<VideosContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

Make those changes, rebuild your project, and the exception should disappear.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:38:30