Setting.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Http;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.DependencyInjection;
  10. namespace EasyTemplate.Tool;
  11. public static class Setting
  12. {
  13. /// <summary>
  14. ///
  15. /// </summary>
  16. private static IConfigurationRoot? configuration;
  17. /// <summary>
  18. /// 获取配置文件
  19. /// </summary>
  20. /// <param name="services"></param>
  21. /// <returns></returns>
  22. public static bool AddConfiguration(this IServiceCollection services)
  23. {
  24. configuration = configuration ?? new ConfigurationBuilder()
  25. .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
  26. .AddJsonFile("Configuration/App.json", optional: true, reloadOnChange: true)
  27. .AddJsonFile("Configuration/DataBase.json", optional: true, reloadOnChange: true)
  28. .AddJsonFile("Configuration/ThirdParty.json", optional: true, reloadOnChange: true)
  29. .Build();
  30. Log.Info("加载配置完成");
  31. return configuration is null;
  32. }
  33. /// <summary>
  34. /// 获取appsettings.json配置信息
  35. /// </summary>
  36. /// <typeparam name="T"></typeparam>
  37. /// <param name="path"></param>
  38. /// <returns></returns>
  39. public static T? Get<T>(string path)
  40. {
  41. try
  42. {
  43. var value = configuration?.GetSection(path).Value;
  44. var result = (T)Convert.ChangeType(value, typeof(T));
  45. return result;
  46. }
  47. catch (Exception)
  48. {
  49. return default;
  50. }
  51. }
  52. /// <summary>
  53. /// 获取appsettings.json配置信息
  54. /// </summary>
  55. /// <typeparam name="T"></typeparam>
  56. /// <param name="path"></param>
  57. /// <returns></returns>
  58. public static IConfigurationSection? GetSection(string path)
  59. {
  60. try
  61. {
  62. return configuration?.GetSection(path);
  63. }
  64. catch (Exception)
  65. {
  66. return default;
  67. }
  68. }
  69. }