PROWAREtech
ASP.NET Core: Use Keys Stored in appsettings.json in .NET 6 and Later
Modify and use appsettings.json keys in ASP.NET Core for custom settings; also, create and use custom JSON files for use in C# web apps.
This article requires .NET 6 as a minimum.
In .NET 6, it was made easy to use the custom keys in appsettings.json. The WebApplicationBuilder
has a configuration object as a property that can be used.
Modify the appsettings.json as in this example.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"MyCustomKey": "Some string value...",
"SecretAuthenticationKey": "396B5DD9-CC75-411C-9311-5B6E1F391B89"
}
Modify the Program.cs as in this example snippet.
var builder = WebApplication.CreateBuilder(args);
// ...
string myCustomKey = builder.Configuration["MyCustomKey"]; // NOTE: do something with myCustomKey
string jwtSecretKey = builder.Configuration["SecretAuthenticationKey"]; // NOTE: use jwtSecretKey for the Secret Key in the JWT Bearer Authentication examples of this site
Alternate/Custom JSON Configuration Files
Also, import custom JSON configuration files to use. Create custom.json as follows.
{
"Custom": {
"Level": {
"Default": "1"
}
},
"SecretAuthenticationKey": "396B5DD9-CC75-411C-9311-5B6E1F391B89"
}
To use the above JSON settings file:
IConfiguration config = new ConfigurationBuilder().AddJsonFile("custom.json").Build(); // NOTE: custom.json could include its full path using Path.Combine() and the ContentRootPath property of the IWebHostEnvironment interface
string myCustomLevelDefault = config["Custom:Level:Default"]; // NOTE: do something with myCustomLevelDefault, which equals "1"
string jwtSecretKey = config["SecretAuthenticationKey"]; // NOTE: use jwtSecretKey for the Secret Key in the JWT Bearer Authentication examples of this site
Comment