2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Reading custom configuration files in .NET Core is a common requirement, especially when the standardappsettings.json
、appsettings.Development.json
orappsettings.Production.json
When the configuration files are not sufficient to meet your application needs, here are the steps to read custom configuration files:
First, create a custom configuration file in your project root directory or wherever you think is appropriate, such asmycustomsettings.json
。
Next, you need to define a class that matches your custom configuration file structure.mycustomsettings.json
The content is as follows:
- {
- "MyCustomSettings": {
- "Key1": "Value1",
- "Key2": "Value2"
- }
- }
You can define the following configuration class:
- public class MyCustomSettings
- {
- public string Key1 { get; set; }
- public string Key2 { get; set; }
- }
-
- public class MyCustomSettingsOptions
- {
- public MyCustomSettings MyCustomSettings { get; set; }
- }
Startup.cs
Configuring and reading configurationexist.NET Core
AppliedStartup.cs
In the file, you need toConfigureServices
method and add it to the dependency injection container.
- public void ConfigureServices(IServiceCollection services)
- {
- // 添加对自定义配置文件的支持
- var builder = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
- .AddJsonFile("mycustomsettings.json", optional: true, reloadOnChange: true); // 添加自定义配置文件
-
- IConfigurationRoot configuration = builder.Build();
-
- // 绑定配置到MyCustomSettingsOptions类
- services.Configure<MyCustomSettingsOptions>(configuration.GetSection("MyCustomSettings"));
-
- // 其他服务配置...
-
- services.AddControllers();
- // 其他配置...
- }
Now you can use it in your controllers or other services via dependency injectionMyCustomSettingsOptions
.
- [ApiController]
- [Route("[controller]")]
- public class MyController : ControllerBase
- {
- private readonly MyCustomSettings _myCustomSettings;
-
- public MyController(IOptions<MyCustomSettingsOptions> options)
- {
- _myCustomSettings = options.Value.MyCustomSettings;
- }
-
- [HttpGet]
- public IActionResult Get()
- {
- // 使用_myCustomSettings...
- return Ok($"Key1: {_myCustomSettings.Key1}, Key2: {_myCustomSettings.Key2}");
- }
- }
By defining a class that matches the structure of your configuration file, and thenStartup.cs
Configure and read these configurations in the application, and finally use these configurations in other parts of the application through dependency injection.