ASP.NET Core 2.0数据库优先模式下connectionString为空异常求助
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
Verify Configuration File Copy Settings
- Right-click your
appsettings.jsonfile 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.
- Right-click your
Confirm Default Configuration Loading
YourMainmethod usesWebHost.CreateDefaultBuilder(args), which in ASP.NET Core 2.0 automatically loadsappsettings.jsonand 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

