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:
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": "…"
}
}
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")));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.