Keywords: ASP.NET Core | appsettings.json | connection string configuration
Abstract: This article provides an in-depth analysis of the "Value cannot be null. Parameter name: connectionString" error encountered when configuring database connection strings in ASP.NET Core 1.0. By examining structural differences in appsettings.json files, it explains how the Configuration.GetConnectionString() method works and offers multiple solutions. The article compares the impact of different JSON structures on configuration reading, including the distinction between using nested "Data" objects and direct "ConnectionStrings" usage, and demonstrates how to correctly access configuration values through key path navigation. Additionally, it discusses cross-platform compatibility issues related to key separators and provides code examples to avoid common spelling mistakes.
Problem Background and Error Analysis
In ASP.NET Core 1.0 application development, developers frequently encounter issues when configuring database connection strings. A typical error scenario occurs when calling Configuration.GetConnectionString("DefaultConnection") in the ConfigureServices method of Startup.cs, resulting in a "Value cannot be null. Parameter name: connectionString" exception. This error typically indicates that the configuration system failed to properly parse the connection string settings in the appsettings.json file.
Structural Differences in appsettings.json
The core issue lies in the mismatch between the structure of the appsettings.json file and the expectations of the ASP.NET Core configuration system. In the original problem, the JSON file used the following structure:
{
"Data": {
"DefaultConnection": {
"ConnectionString": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"
}
},
"Logging": { ... }
}
However, ASP.NET Core's GetConnectionString() extension method expects a different structure by default:
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": { ... }
}
This structural difference causes configuration reading to fail. It's worth noting that when adding an "ASP.NET Configuration File" in Visual Studio, the system automatically generates the latter structure, explaining why many example codes work correctly.
Solution 1: Using Key Path Navigation
If maintaining the original nested "Data" object structure, the connection string can be accessed through key path navigation:
var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
Here, a colon (:) is used as the separator instead of a dot (.), addressing cross-platform compatibility issues. File paths and configuration keys are parsed differently in Windows and Linux systems, and using colons ensures consistency.
Solution 2: Standardizing JSON Structure
A more recommended approach is to modify the appsettings.json file to the standard structure:
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": { ... }
}
After modification, the GetConnectionString() method can be used directly:
var connStr = Configuration.GetConnectionString("DefaultConnection");
From an implementation perspective, the GetConnectionString() method internally executes Configuration["ConnectionStrings:DefaultConnection"], making the two approaches equivalent.
Common Mistakes and Considerations
Beyond structural issues, developers should be aware of the following common errors:
- Property Name Spelling Errors: The
GetConnectionStringmethod looks for "ConnectionStrings" (with an s), not "ConnectionString". This is an easily overlooked detail. - Environment-Specific Configuration: In the
Startupconstructor, besides loadingappsettings.json, environment-specific configuration files likeappsettings.Development.jsonshould also be loaded to ensure correct configuration across different environments. - Configuration Reloading: Using
AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)allows automatic configuration reloading when the file changes, which is useful during development.
Code Examples and Best Practices
The following is a complete Startup.cs configuration example demonstrating how to correctly set up and read connection strings:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
// Standard structure reading approach
var connStr = Configuration.GetConnectionString("DefaultConnection");
// Alternative key path approach (for non-standard structures)
// var connStr = Configuration["Data:DefaultConnection:ConnectionString"];
if (string.IsNullOrEmpty(connStr))
{
throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
}
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connStr));
}
In real-world projects, it's recommended to store sensitive information like connection strings in environment variables or secure storage like Azure Key Vault rather than directly in configuration files.
Conclusion
The key to resolving connection string configuration issues in ASP.NET Core lies in understanding the expected structure of the configuration system. By standardizing the appsettings.json file structure or using correct key path navigation, developers can avoid the "Value cannot be null" error. Additionally, paying attention to property name spelling and cross-platform compatibility issues, along with implementing appropriate error handling mechanisms, helps build more robust application configuration systems.