Reputation: 414
I'm building my own API web app using ASP.NET Core 2.0. But I cannot get my connection string stored in appsettings.json
.
Here is my code in the Startup.cs
file, the connection
variable holds the connection string, but somehow it is always null:
public void ConfigureServices(IServiceCollection services) {
//Add connection to SQL Server Db in appsettings.json
var connection = Configuration.GetConnectionString("CoinToolDbContext");
services.AddDbContext<CoinToolDbContext>(options => options.UseSqlServer(connection));
services.AddMvc();
}
And here is my appsettings.json
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"CoinToolDbContext": "Data Source=localhost;Initial Catalog=CoinToolDb;Integrated Security=True;Pooling=False"
}
}
}
And here is my project folder and file structure:
Upvotes: 2
Views: 4606
Reputation: 645
Move the ConnectionStrings element outside the Logging section (The closing bracket was in the wrong place)
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
},
},
"ConnectionStrings": {
"CoinToolDbContext": "Data Source=localhost;Initial Catalog=CoinToolDb;Integrated Security=True;Pooling=False"
}
}
And setup the context this way:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CoinToolDbContext>(options.UseSqlServer(Configuration.GetConnectionString("CoinToolDbContext")));
}
Upvotes: 2
Reputation: 387647
In your appsettings.json
, the ConnectionStrings
section is within the Logging
section. So you cannot resolve the connection strings from the root IConfiguration
object.
You should change your configuration so that ConnectionStrings
is at the root:
{
"Logging": {
…
},
"ConnectionStrings": {
"CoinToolDbContext": "…"
}
}
Upvotes: 4