Appsettings.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using Microsoft.Extensions.Configuration;
  2. using Microsoft.Extensions.Configuration.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace Ropin.Inspection.Common.Helper
  9. {
  10. /// <summary>
  11. /// appsettings.json操作类
  12. /// </summary>
  13. public class Appsettings
  14. {
  15. static IConfiguration Configuration { get; set; }
  16. static string contentPath { get; set; }
  17. public Appsettings(string contentPath)
  18. {
  19. string Path = "appsettings.json";
  20. //如果你把配置文件 是 根据环境变量来分开了,可以这样写
  21. //Path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json";
  22. Configuration = new ConfigurationBuilder()
  23. .SetBasePath(contentPath)
  24. .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })//这样的话,可以直接读目录里的json文件,而不是 bin 文件夹下的,所以不用修改复制属性
  25. .Build();
  26. }
  27. public Appsettings(IConfiguration configuration)
  28. {
  29. Configuration = configuration;
  30. }
  31. /// <summary>
  32. /// 封装要操作的字符
  33. /// </summary>
  34. /// <param name="sections">节点配置</param>
  35. /// <returns></returns>
  36. public static string app(params string[] sections)
  37. {
  38. try
  39. {
  40. if (sections.Any())
  41. {
  42. return Configuration[string.Join(":", sections)];
  43. }
  44. }
  45. catch (Exception) { }
  46. return "";
  47. }
  48. /// <summary>
  49. /// 递归获取配置信息数组
  50. /// </summary>
  51. /// <typeparam name="T"></typeparam>
  52. /// <param name="sections"></param>
  53. /// <returns></returns>
  54. public static List<T> app<T>(params string[] sections)
  55. {
  56. List<T> list = new List<T>();
  57. // 引用 Microsoft.Extensions.Configuration.Binder 包
  58. Configuration.Bind(string.Join(":", sections), list);
  59. return list;
  60. }
  61. /// <summary>
  62. /// 根据路径 configuration["App:Name"];
  63. /// </summary>
  64. /// <param name="sectionsPath"></param>
  65. /// <returns></returns>
  66. public static string GetValue(string sectionsPath)
  67. {
  68. try
  69. {
  70. return Configuration[sectionsPath];
  71. }
  72. catch (Exception) { }
  73. return "";
  74. }
  75. }
  76. }