I'm trying to read the appsetting on my console application as well as to set he EntityFramework connection string.
I did a lot of google but did not found any single solution not even on Microsoft's documentation.
Here is the my questions.
string connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<MyDBContext>(option =>option.UseSqlServer(connectionString, m => m.MigrationsAssembly("MyMVCDLL"))); services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
Can someone help me with this.
Add Json File After adding the file, right click on appsettings. json and select properties. Then set “Copy to Ouptut Directory” option to Copy Always. Add few settings to json file, so that you can verify that those settings are loaded.
Create a new console project. Add an appsettings. json file to the project. Right click, select properties and ensure its copied to output directory.
First, don't save sensitive data (login, password, API keys) in appsettings.json
, as you can accidentally commit it to Verison Control and hence risk your credentials leaking. For this you have to use User Secrets tool for development, see the User Secret documentation for details.
Second, read the tooltip documentation of Configuration.GetConnectionString("DefaultConnection");
method. It clearly states that `GetConnectionString is a
Shorthand for GetSection(“ConnectionStrings”)[name]
That being said, your appsettings.json has to look like this:
{
...,
"ConnectionStrings":
{
"DefaultConnection" : "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"
}
}
or when using user secrets:
dotnet user-secrets set ConnectionStrings:DefaultConnection Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Using it in the console application is exactly the same. The configuration package isn't ASP.NET Core specific and can be used on its own.
The required packages are (depending on which of them 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 to build the configuration is exactly the same as in ASP.NET Core. Just instead of doing it in Startup.cs
you do it in the Main
method:
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
// You can't use environment specific configuration files like this
// becuase IHostingEnvironment is an ASP.NET Core specific interface
//.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddUserSecrets()
.AddEnvironmentVariables();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With