AppSettings.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. namespace Base
  2. {
  3. public class AppSettings
  4. {
  5. static IConfiguration Configuration { get; set; }
  6. public AppSettings(IConfiguration configuration)
  7. {
  8. Configuration = configuration;
  9. }
  10. /// <summary>
  11. /// 封装要操作的字符
  12. /// </summary>
  13. /// <param name="sections">节点配置</param>
  14. /// <returns></returns>
  15. public static string App(params string[] sections)
  16. {
  17. try
  18. {
  19. if (sections.Any())
  20. {
  21. return Configuration[string.Join(":", sections)];
  22. }
  23. }
  24. catch (Exception ex)
  25. {
  26. Console.WriteLine(ex.Message);
  27. }
  28. return "";
  29. }
  30. /// <summary>
  31. /// 递归获取配置信息数组
  32. /// </summary>
  33. /// <typeparam name="T"></typeparam>
  34. /// <param name="sections"></param>
  35. /// <returns></returns>
  36. public static List<T> App<T>(params string[] sections)
  37. {
  38. List<T> list = new();
  39. try
  40. {
  41. if (Configuration != null && sections.Any())
  42. {
  43. Configuration.Bind(string.Join(":", sections), list);
  44. }
  45. }
  46. catch
  47. {
  48. return list;
  49. }
  50. return list;
  51. }
  52. public static T Bind<T>(string key, T t)
  53. {
  54. Configuration.Bind(key, t);
  55. return t;
  56. }
  57. public static T GetAppConfig<T>(string key, T defaultValue = default)
  58. {
  59. T setting = (T)Convert.ChangeType(Configuration[key], typeof(T));
  60. var value = setting;
  61. if (setting == null)
  62. value = defaultValue;
  63. return value;
  64. }
  65. /// <summary>
  66. /// 获取配置文件
  67. /// </summary>
  68. /// <param name="key">eg: WeChat:Token</param>
  69. /// <returns></returns>
  70. public static string GetConfig(string key)
  71. {
  72. return Configuration[key];
  73. }
  74. /// <summary>
  75. /// 获取配置节点并转换成指定类型
  76. /// </summary>
  77. /// <typeparam name="T">节点类型</typeparam>
  78. /// <param name="key">节点路径</param>
  79. /// <returns>节点类型实例</returns>
  80. public static T Get<T>(string key)
  81. {
  82. return Configuration.GetSection(key).Get<T>();
  83. }
  84. }
  85. }