First, do not save sensitive data (username, password, API keys) in appsettings.json
, as you may accidentally pass it to Verison Control and, therefore, the risk of leakage of your credentials. To do this, you need to use the User Secrets tool for development, for more details see the Secret user documentation .
Second, read the documentation at the tip of the Configuration.GetConnectionString("DefaultConnection");
method Configuration.GetConnectionString("DefaultConnection");
. It clearly states that `GetConnectionString -
Shortcut for GetSection ("ConnectionStrings") [name]
In doing so, your appsettings.json should look like this:
{ ..., "ConnectionStrings": { "DefaultConnection" : "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;" } }
or when using user secrets:
dotnet user secrets set by ConnectionStrings: DefaultConnection Server = myServerAddress; Database = myDataBase; Trusted_Connection = True;
Update
Using it in a console application is exactly the same. The configuration package is not specific to ASP.NET Core and can be used on its own.
Required packages (depending on which one you want to use
"Microsoft.Extensions.Configuration": "1.0.0", "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0", "Microsoft.Extensions .Configuration.Json ":" 1.0.0 "," Microsoft.Extensions.Configuration.UserSecrets ":" 1.0.0 ",
And the code for creating the configuration is exactly the same as in ASP.NET Core. Instead, in Startup.cs
you do this in the Main
method:
var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)