PROWAREtech








ASP.NET Core: Use Keys Stored in appsettings.json in .NET 6
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.
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..."
}
Modify the Program.cs as in this example snippet.
var builder = WebApplication.CreateBuilder(args);
// ...
string myCustomKey = builder.Configuration["MyCustomKey"]; // NOTE: do something with myCustomKey
Alternate/Custom JSON Configuration Files
Also, import custom JSON configuration files to use. Create custom.json as follows.
{
"Custom": {
"Level": {
"Default": "1"
}
}
}
To use the above JSON settings file:
IConfiguration config = new ConfigurationBuilder().AddJsonFile("custom.json").Build(); // NOTE: custom.json should be in the same folder as Program.cs
string myCustomLevelDefault = config["Custom:Level:Default"]; // NOTE: do something with myCustomLevelDefault, which equals "1"
Comment