一、前言

在项目开发过程中,不可避免的会设置一些全局的可变的参数,如连接字符串、功能开关、Swagger配置、Redis配置等等。 .NET Core 将这些配置参数统一放在 appsettings.json 文件中进行管理,并提供了 IConfiguration 接口,在需要读取配置文件内容的类中,注入 IConfiguration 即可。 但是,.NET Core 默认是通过构造函数注入,而 appsettings.json 的内容是不会经常进行变动,如果每个需要获取配置值类,都先在构造函数注入 IConfiguration 才能使用,也挺烦的。 所以本篇文章介绍多种获取配置文件的方法。后面也会展示如何写一个公用类,对配置的读取进行简单的封装。

二、读取配置文件

1、Json配置文件说明

1. 配置文件

.NET Core | 读取配置文件 - 图1

配置文件指的是appsettings.json,不是 launchSettings.json,不要把json内容放错地方了。
2. json配置文件示例
  1. {
  2. "Logging": {
  3. "LogLevel": {
  4. "Default": "Information",
  5. "Microsoft": "Warning",
  6. "Microsoft.Hosting.Lifetime": "Information"
  7. }
  8. },
  9. "Setting": {
  10. "Url": "http://localhost:8080/",
  11. "Name": "localhost"
  12. }
  13. }

2、读取配置文件的几种方式

1. 通过依赖注入直接读取

通过依赖注入的方式

  1. [ApiController]
  2. [Route("[controller]/[action]")]
  3. public class TestController: ControllerBase
  4. {
  5. public IConfiguration _configuration { get; set; }
  6. public TestController(IConfiguration configuration)
  7. {
  8. _configuration = configuration;
  9. }
  10. /// <summary>
  11. /// 方式一:直接读取单个值
  12. /// </summary>
  13. [HttpGet, HttpPost]
  14. public void GetConfigDemo1()
  15. {
  16. var url = _configuration["Setting:Url"]; // http://localhost:8080/
  17. var url2 = _configuration.GetValue<string>("Setting:Url"); // http://localhost:8080/
  18. var url3 = _configuration.GetSection("Setting").GetSection("Url").Value; // http://localhost:8080/
  19. }
  20. }
2. 读取Json对象
如果想把json对象拿去使用的话,一般都是转成类去使用,毕竟对于类在熟悉不过了,方便又熟练 1)新建Json模块Setting类
  1. /// <summary>
  2. /// Json模块Setting类
  3. /// </summary>
  4. public class SettingClass
  5. {
  6. /// <summary>
  7. /// 地址
  8. /// </summary>
  9. public string Url { get; set; }
  10. /// <summary>
  11. /// 名称
  12. /// </summary>
  13. public string Name { get; set; }
  14. }
2)新建应用设置类AppSettings
  1. /// <summary>
  2. /// 应用设置类
  3. /// 总类:对应json文件,确定json模块与对象
  4. /// 这里负责一一绑定json模块与对象
  5. /// </summary>
  6. public static class AppSettings
  7. {
  8. public static SettingClass settingClass { get; set; }
  9. public static void Init(IConfiguration configuration)
  10. {
  11. // 将Setting模块绑定到Json模块的Setting类
  12. settingClass = new SettingClass();
  13. configuration.Bind("Setting", settingClass);
  14. }
  15. }
3)在Startup.cs中调用AppSettings的初始化方法

.NET Core | 读取配置文件 - 图2

  1. // AppSettings总类进行调用静态方法
  2. AppSettings.Init(Configuration);
4)在控制器中使用(静态类 静态变量)
  1. [ApiController]
  2. [Route("[controller]/[action]")]
  3. public class TestController: ControllerBase
  4. {
  5. public IConfiguration _configuration { get; set; }
  6. public TestController(IConfiguration configuration)
  7. {
  8. _configuration = configuration;
  9. }
  10. /// <summary>
  11. /// 方式二:读取Json对象 - 变成类使用
  12. /// </summary>
  13. [HttpGet, HttpPost]
  14. public void GetConfigDemo2()
  15. {
  16. var url = AppSettings.settingClass.Url; // http://localhost:8080/
  17. var name = AppSettings.settingClass.Name; // localhost
  18. }
  19. }
3. 在注册服务中绑定实体类与Json文件,使用时声明为全局常量
1)在Startup.cs中将Json模块类与Json文件对应内容绑定(Json模块类如方式2的SettingClass类)

.NET Core | 读取配置文件 - 图3

将注册服务的时候把 配置文件 与类 绑定好值,然后在使用的时候去用
  1. services.Configure<SettingClass> (option =>
  2. {
  3. option.Url = Configuration["Setting:Url"];
  4. option.Name = Configuration["Setting:Name"];
  5. });
2)在控制器中使用 在用的地方IOptions
  1. [ApiController]
  2. [Route("[controller]/[action]")]
  3. public class TestController: ControllerBase
  4. {
  5. public IConfiguration _configuration { get; set; }
  6. public string UrlStr { get; set; }
  7. public string NameStr { get; set; }
  8. public TestController(IConfiguration configuration, IOptions<SettingClass> settings)
  9. {
  10. _configuration = configuration;
  11. UrlStr = settings.Value.Url;
  12. NameStr = settings.Value.Name;
  13. }
  14. /// <summary>
  15. /// 方法三:在注册服务的时候把配置文件与类绑定好值,使用时声明为全局常量
  16. /// </summary>
  17. [HttpGet, HttpPost]
  18. public void GetConfigDemo3()
  19. {
  20. var url = UrlStr; // http://localhost:8080/
  21. var name = NameStr; // localhost
  22. }
  23. }

更多方式请看一下文章:

  1. Asp.Net Core 读取配置文件的多种方式 看这一篇就够了!
  2. .Net Core获取自定义配置文件信息

三、公用类的封装

1、获取配置信息设置为全局变量

1. 声明一个静态类Common.cs
  1. using System;
  2. using System.IO;
  3. using Microsoft.Extensions.Configuration;
  4. namespace test
  5. {
  6. public static class Common
  7. {
  8. public static string CommonUrl;
  9. static Common()
  10. {
  11. var builder = new ConfigurationBuilder()
  12. .SetBasePath(Directory.GetCurrentDirectory())
  13. .AddJsonFile("appsettings.json");
  14. var config = builder.Build();
  15. var commonurl = config["CommonUrl"];
  16. CommonUrl = commonurl;
  17. }
  18. }
  19. }
2. 使用
  1. Common.CommonUrl;

2、Json转类封装

1. 新建公共类:AppSettings.cs
新建文件夹 Helper 文件夹,帮助类都放此文件夹中。添加类 AppSettings.cs
  1. using Microsoft.Extensions.Configuration;
  2. namespace AMO.Core.Helper
  3. {
  4. /// <summary>
  5. /// 读取配置文件帮助类
  6. /// </summary>
  7. public class AppSettings
  8. {
  9. #region 注入参数
  10. /// <summary>
  11. /// 配置文件
  12. /// </summary>
  13. private static IConfiguration? _config;
  14. #endregion
  15. #region 构造函数
  16. /// <summary>
  17. /// 构造函数
  18. /// </summary>
  19. /// <param name="configuration">配置文件</param>
  20. public AppSettings()
  21. {
  22. _config = new ConfigurationBuilder()
  23. .AddJsonFile("appsettings.json", true, reloadOnChange: true)
  24. .Build();
  25. }
  26. #endregion
  27. #region 静态方法
  28. /// <summary>
  29. /// 读取指定节点信息
  30. /// </summary>
  31. /// <param name="sessions">节点名称</param>
  32. /// <returns></returns>
  33. public static string ReadString(params string[] sessions)
  34. {
  35. try
  36. {
  37. if (_config != null && sessions.Any())
  38. {
  39. string? str = _config[string.Join(":", sessions)];
  40. if (!string.IsNullOrEmpty(str))
  41. {
  42. return str;
  43. }
  44. }
  45. }
  46. catch
  47. {
  48. return string.Empty;
  49. }
  50. return string.Empty;
  51. }
  52. /// <summary>
  53. /// 读取实体信息
  54. /// </summary>
  55. /// <param name="sessions">节点名称</param>
  56. /// <returns></returns>
  57. public static T ReadObject<T>(params string[] sessions) where T : class, new()
  58. {
  59. T data = new();
  60. try
  61. {
  62. if (_config != null && sessions.Any())
  63. {
  64. _config.Bind(string.Join(":", sessions), data);
  65. }
  66. }
  67. catch
  68. {
  69. return data;
  70. }
  71. return data;
  72. }
  73. /// <summary>
  74. /// 读取实体数组信息
  75. /// </summary>
  76. /// <param name="sessions">节点名称</param>
  77. /// <returns></returns>
  78. public static List<T> ReadList<T>(params string[] sessions) where T : class
  79. {
  80. List<T> list = new();
  81. try
  82. {
  83. if (_config != null && sessions.Any())
  84. {
  85. _config.Bind(string.Join(":", sessions), list);
  86. }
  87. }
  88. catch
  89. {
  90. return list;
  91. }
  92. return list;
  93. }
  94. #endregion
  95. }
  96. }
2. 注册服务
  1. public static void Run(this WebApplicationBuilder builder)
  2. {
  3. var logger = NLog.LogManager.Setup().GetCurrentClassLogger();
  4. logger.Debug("[启动服务]");
  5. try
  6. {
  7. // 配置文件,放在第一句,并注册为Singleton
  8. builder.Services.AddSingleton(new AppSettings());
  9. // ... 其他
  10. }
  11. }
3. 使用
修改 appsettings.json 添加测试配置
  1. /* 单值 */
  2. "FileLoad": "/nginx/fileload",
  3. /* 对象 */
  4. "Redis": {
  5. "Enabled": true,
  6. "ConnectionString": "127.0.0.1:6379,ssl=false,abortConnect=false,connectTimeout=5000",
  7. "DatabaseId": 10
  8. }
定义 Redis 配置类, 类中属性记得给默认值,避免在使用的时候出现 null 的情况。
  1. public class RedisConfig
  2. {
  3. public bool Enabled { get; set; } = false;
  4. public string ConnectionString { get; set; } = "127.0.0.1:6379,ssl=false,abortConnect=false,connectTimeout=5000";
  5. public int DatabaseId { get; set; } = 10;
  6. }
Controller 写测试接口
  1. [HttpGet("read-string")]
  2. public string ReadString(string key)
  3. {
  4. string data = AppSettings.ReadString(key);
  5. return data;
  6. }
  7. [HttpGet("read-object")]
  8. public RedisConfig ReadObject(string key)
  9. {
  10. RedisConfig data = AppSettings.ReadObject<RedisConfig>(key);
  11. return data;
  12. }
测试结果:
  1. 获取对象
  2. [Request URL] http://localhost:5118/WeatherForecast/read-object?key=Redis
  3. [Server response]
  4. {
  5. "enabled": true,
  6. "connectionString": "127.0.0.1:6379,ssl=false,abortConnect=false,connectTimeout=5000",
  7. "databaseId": 10
  8. }
  9. 获取单值
  10. [Request URL] http://localhost:5118/WeatherForecast/read-string?key=FileLoad
  11. [Server response] /nginx/fileload
以上,对 appsettings.json 进行了简单封装。你可以在任何需要获取配置的类中使用 AppSettings。