How to use configuration providers in ASP.NET Core
By FoxLearn 1/4/2025 2:51:39 AM 44
As an open-source, cross-platform framework, ASP.NET Core is designed for high-performance, scalable web applications. Configuration data is stored as key-value pairs, allowing for a hierarchical, multi-level structure to manage settings efficiently.
When a new ASP.NET Core project is created, two files appsettings.json and appsettings.Development.json are automatically configured.
Starting with ASP.Net Core 2.0, you can now configure data in the Program.cs file, eliminating the need to restrict configuration to Startup.cs.
public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); }
Using the JSON configuration provider in ASP.NET Core
You can utilize the appsettings.json file to store configuration data such as API keys, service URLs, or application-specific settings.
Here's an example showing how to add the appsettings.json file using the AddJsonFile
method of the IConfigurationBuilder
instance.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.SetBasePath(env.ContentRootPath); config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); }) .UseStartup<Startup>();
Let's assume your appsettings.json file contains the following configuration:
{ "Database": { "ConnectionString": "Server=myServer;Database=myDB;User=myUser;Password=myPass;" }, "ApiSettings": { "BaseUrl": "https://api.example.com", "ApiKey": "12345" } }
To retrieve values from this configuration file, you need to inject an instance of IConfiguration
into your controller. Below is how you can access the configuration values:
public class SettingsController : ControllerBase { IConfiguration _configuration; public SettingsController(IConfiguration configuration) { _configuration = configuration; } [HttpGet] public ActionResult<string> GetApiBaseUrl() { var apiBaseUrl = _configuration["ApiSettings:BaseUrl"]; return apiBaseUrl; } [HttpGet("connection")] public ActionResult<string> GetDatabaseConnectionString() { var connectionString = _configuration["Database:ConnectionString"]; return connectionString; } }
In this example, the SettingsController class uses IConfiguration
to retrieve values from the ApiSettings and Database sections of the appsettings.json file.
If you want to further organize your settings, you can create an additional configuration file, such as appsettings.custom.json, to manage other data separately.
Here’s how you can load both the default appsettings.json and the custom appsettings.custom.json files:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; string pathToSettingsFile = env.ContentRootPath; config.SetBasePath(env.ContentRootPath); config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); config.AddJsonFile(Path.Combine(pathToSettingsFile, "appsettings.custom.json"), optional: true); }) .UseStartup<Startup>();
In this setup, both the appsettings.json and the appsettings.custom.json files are loaded, allowing you to structure your configuration more flexibly and manage different environments and settings in separate files.
Using the memory configuration provider in ASP.NET Core
The memory configuration provider allows you to store and access configuration data directly in memory, without needing a physical file. This can be useful for storing temporary or dynamic data.
Here's an example of how to store configuration data in memory using the memory provider:
var builder = new ConfigurationBuilder(); var authorProfile = new Dictionary<string, string> { {"AuthorProfile:FirstName", "John"}, {"AuthorProfile:LastName", "Doe"}, {"AuthorProfile:City", "New York"} }; builder.AddInMemoryCollection(authorProfile); Configuration = builder.Build();
In this example, a dictionary is used to store author profile information, and the data is added to the configuration builder using the AddInMemoryCollection
method. Once the configuration is built, you can retrieve the values like this:
var firstName = _configuration["AuthorProfile:FirstName"];
In ASP.Net Core, configuration data does not automatically refresh when it is changed. If you need to reload the data, you can either restart the application or explicitly call the Reload()
method, which is part of the IConfigurationRoot
interface in the Microsoft.Extensions.Configuration
namespace.
if (Configuration is IConfigurationRoot configurationRoot) { configurationRoot.Reload(); }
The Reload()
method allows you to refresh the configuration data from the underlying providers.
Additionally, the IConfigurationBuilder
interface offers various extension methods that make it easy to work with configuration data stored in different formats like JSON, XML, or INI files.
- Content Negotiation in Web API
- How to fix 'InvalidOperationException: Scheme already exists: Bearer'
- How to fix System.InvalidOperationException: Scheme already exists: Identity.Application
- Add Thread ID to the Log File using Serilog
- Handling Exceptions in .NET Core API with Middleware
- InProcess Hosting in ASP.NET Core
- Limits on ThreadPool.SetMinThreads and SetMaxThreads
- Controlling DateTime Format in JSON Output with JsonSerializerOptions