Technology Sharing

.Net core implements reading custom configuration files

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Reading custom configuration files in .NET Core is a common requirement, especially when the standardappsettings.jsonappsettings.Development.jsonorappsettings.Production.jsonWhen the configuration files are not sufficient to meet your application needs, here are the steps to read custom configuration files:

1. Create a custom configuration file

First, create a custom configuration file in your project root directory or wherever you think is appropriate, such asmycustomsettings.json

2. Define the configuration class

Next, you need to define a class that matches your custom configuration file structure.mycustomsettings.jsonThe content is as follows:

  1. {
  2. "MyCustomSettings": {
  3. "Key1": "Value1",
  4. "Key2": "Value2"
  5. }
  6. }

You can define the following configuration class:

  1. public class MyCustomSettings
  2. {
  3. public string Key1 { get; set; }
  4. public string Key2 { get; set; }
  5. }
  6. public class MyCustomSettingsOptions
  7. {
  8. public MyCustomSettings MyCustomSettings { get; set; }
  9. }

3. InStartup.csConfiguring and reading configuration

exist.NET CoreAppliedStartup.csIn the file, you need toConfigureServicesmethod and add it to the dependency injection container.

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. // 添加对自定义配置文件的支持
  4. var builder = new ConfigurationBuilder()
  5. .SetBasePath(Directory.GetCurrentDirectory())
  6. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  7. .AddJsonFile("mycustomsettings.json", optional: true, reloadOnChange: true); // 添加自定义配置文件
  8. IConfigurationRoot configuration = builder.Build();
  9. // 绑定配置到MyCustomSettingsOptions类
  10. services.Configure<MyCustomSettingsOptions>(configuration.GetSection("MyCustomSettings"));
  11. // 其他服务配置...
  12. services.AddControllers();
  13. // 其他配置...
  14. }

4. Inject and use configuration in controllers or other classes

Now you can use it in your controllers or other services via dependency injectionMyCustomSettingsOptions.

  1. [ApiController]
  2. [Route("[controller]")]
  3. public class MyController : ControllerBase
  4. {
  5. private readonly MyCustomSettings _myCustomSettings;
  6. public MyController(IOptions<MyCustomSettingsOptions> options)
  7. {
  8. _myCustomSettings = options.Value.MyCustomSettings;
  9. }
  10. [HttpGet]
  11. public IActionResult Get()
  12. {
  13. // 使用_myCustomSettings...
  14. return Ok($"Key1: {_myCustomSettings.Key1}, Key2: {_myCustomSettings.Key2}");
  15. }
  16. }

By defining a class that matches the structure of your configuration file, and thenStartup.csConfigure and read these configurations in the application, and finally use these configurations in other parts of the application through dependency injection.