Cannot get connection string from appsettings.json

asp.net-core c# entity-framework-core

Question

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:

Solution structure in Visual Studio with the appsettings file at the root

1
1
2/18/2018 2:41:30 PM

Accepted Answer

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")));
}
2
2/18/2018 1:04:44 PM

Popular Answer

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": "…"
  }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow