首页 > 其他分享 >net core 动态设置appsettings.json

net core 动态设置appsettings.json

时间:2022-10-10 11:58:10浏览次数:59  
标签:core JObject jsonObject json key appsettings var new data

配置基类

该类主要用于判断传递的值是否为类对象,方便赋值

1     public interface IBaseConfigEntity
2     {
3 
4     }

 

配置类

 建立配置存储类

1     public class Test : IBaseConfigEntity
2     {
3         public string Name { get; set; }
4     }

 

帮助类

用于更改appsettings.json配置文件

 1 public class ConfigUtils
 2     {
 3         public static bool UpdateConfig<T>(Dictionary<string, T> sectionInfo, string configFileName = "appsettings.json")
 4         {
 5             var type = typeof(T);
 6             if (sectionInfo.Count == 0)
 7             {
 8                 return false;
 9             }
10             try
11             {
12                 var filePath = Path.Combine(Directory.GetCurrentDirectory(), configFileName);
13                 JObject jsonObject;
14                 if (File.Exists(filePath))
15                 {
16                     using (var file = new StreamReader(filePath))
17                     {
18                         using (var reader = new JsonTextReader(file))
19                         {
20                             jsonObject = (JObject)JToken.ReadFrom(reader);
21                         }
22                     }
23                 }
24                 else
25                 {
26                     jsonObject = new JObject();
27                 }
28 
29                 foreach (var key in sectionInfo.Keys)
30                 {
31                     var data = sectionInfo[key];
32                     if (key.Contains(":"))
33                     {
34                         GetValueByKey(jsonObject, key, data, type);
35                     }
36                     else
37                     {
38                         if (typeof(IBaseConfigEntity).IsAssignableFrom(type))
39                         {
40                             jsonObject[key] = JObject.FromObject(sectionInfo[key]);
41                         }
42                         else
43                         {
44                             jsonObject[key] = data.ToString();
45                         }
46                     }
47 
48                 }
49 
50                 using (var writer = new StreamWriter(filePath))
51                 using (var jsonwriter = new JsonTextWriter(writer)
52                 {
53                     Formatting = Formatting.Indented,//格式化缩进
54                     Indentation = 4,  //缩进四个字符
55                     IndentChar = ' '  //缩进的字符是空格
56                 })
57                 {
58                     jsonObject.WriteTo(jsonwriter);
59                     return true;
60                 }
61             }
62             catch (Exception)
63             {
64                 return false;
65             }
66         }
67 
68 
69         /// <summary>
70         /// 根据key设置值
71         /// </summary>
72         /// <param name="jsonObject"></param>
73         /// <param name="key"></param>
74         private static void GetValueByKey<T>(JObject jsonObject, string key, T data, Type type)
75         {
76             var keys = key.Split(":");
77             if (keys.Length > 1)
78             {
79                 var value = (JObject)jsonObject[keys[0]];
80                 GetValueByKey(value, key.Replace($"{keys[0]}:", ""), data, type);
81             }
82             else
83             {
84                 if (typeof(IBaseConfigEntity).IsAssignableFrom(type))
85                 {
86                     jsonObject[key] = JObject.FromObject(data);
87                 }
88                 else
89                 {
90                     jsonObject[key] = data.ToString();
91                 }
92             }
93 
94         }
95     }


调用方式1
"test:key" 表示appsettings中 test 下的key配置, 可一次性多个传入,传入的值可以是对象也可以是字符串
1         var s = new Test
2             {
3                 Name = "123"
4             };
5             ConfigUtils.UpdateConfig(new Dictionary<string, Test>
6             {
7                 {"test:key",s},
8             });

 

调用方式2
1     ConfigUtils.UpdateConfig(new Dictionary<string, string>
2             {
3                 {"test:key","我是需要修改的值"},
4             });

修改后效果

{
    "test": {
        "key": {
            "Name": "123"
        }
    }
}

 

 

 

public class ConfigUtils{public static bool UpdateConfig<T>(Dictionary<string, T> sectionInfo, string configFileName = "appsettings.json"){var type = typeof(T);if (sectionInfo.Count == 0){return false;}try{var filePath = Path.Combine(Directory.GetCurrentDirectory(), configFileName);JObject jsonObject;if (File.Exists(filePath)){using (var file = new StreamReader(filePath)){using (var reader = new JsonTextReader(file)){jsonObject = (JObject)JToken.ReadFrom(reader);}}}else{jsonObject = new JObject();}
foreach (var key in sectionInfo.Keys){var data = sectionInfo[key];if (key.Contains(":")){GetValueByKey(jsonObject, key, data, type);}else{if (typeof(IBaseConfigEntity).IsAssignableFrom(type)){jsonObject[key] = JObject.FromObject(sectionInfo[key]);}else{jsonObject[key] = data.ToString();}}
}
using (var writer = new StreamWriter(filePath))using (var jsonwriter = new JsonTextWriter(writer){Formatting = Formatting.Indented,//格式化缩进Indentation = 4,  //缩进四个字符IndentChar = ' '  //缩进的字符是空格}){jsonObject.WriteTo(jsonwriter);return true;}}catch (Exception){return false;}}

/// <summary>/// 根据key设置值/// </summary>/// <param name="jsonObject"></param>/// <param name="key"></param>private static void GetValueByKey<T>(JObject jsonObject, string key, T data, Type type){var keys = key.Split(":");if (keys.Length > 1){var value = (JObject)jsonObject[keys[0]];GetValueByKey(value, key.Replace($"{keys[0]}:", ""), data, type);}else{if (typeof(IBaseConfigEntity).IsAssignableFrom(type)){jsonObject[key] = JObject.FromObject(data);}else{jsonObject[key] = data.ToString();}}
}}

标签:core,JObject,jsonObject,json,key,appsettings,var,new,data
From: https://www.cnblogs.com/GoingForward0923/p/16775094.html

相关文章