I am trying to write my connection string in my appsettings.json file and bring it into my startup file but I keep getting a Value cannot be null. Parameter name: connection
I experienced this problem using asp.net core 3.0. The workaround fix for me is:
var connectionString = Configuration["ConnectionStrings:DefaultConnection"];
var connectionString = Configuration["ConnectionStrings::DefaultConnection"];
The emphasis here is the double colon in the connection configuration.
While using Postgres SQL the appsettings.Development.json must contain
"ConnectionStrings": {
"DefaultConnection": "User ID=user;Password=xxxx;Host=127.0.0.1;Port=5432;Database=abc;Pooling=true"
}
Content in the Startup.cs file would be like
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>
(p => p.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
}
I got this because I had a connection string with a \
in it, which needed escaping to be a \\
. So my localdb connection string was causing a load error like this:
"DefaultConnection": "Server=(localdb)\myinstance;Integrated Security=true;Initial Catlog=my-localdb;"
and was fixed by making it:
"DefaultConnection": "Server=(localdb)\\myinstance;Integrated Security=true;Initial Catlog=my-localdb;"
I fought with the null connection string issue far too long, only to find I was doing this:
builder.Services.AddDbContext<MlDataContext>(provider => new MlDataContext(config.GetConnectionString("ConnectionStrings:SqlConnectionString")));
I was using both the ConnectionStrings:
prefix AND GetConnectionString
. When I removed the prefix it worked:
builder.Services.AddDbContext<MlDataContext>(options => options.UseSqlServer(config.GetConnectionString("SqlConnectionString")));
DefaultConnection
is the inner object in the json structure and it is the child of Data
object.
So if you want to be exact with your config file you can use
var connStr = Configuration.GetSection("Data")
.GetSection("DefaultConnection")["ConnectionString"];
I had got similar error.My "appsettings.json" file was not loading because the properties of the file was Copy to Output Directory -> Do not Copy. I set that to Copy always save and rebuild.It worked.