asp.net core 读取配置文件AppSettings.json

新建类

 1 namespace webc.Utils
 2 {
 3     public class AppHelper
 4     {
 5         private static IConfiguration? _config;
 6 
 7         public AppHelper(IConfiguration configuration)
 8         {
 9             _config = configuration;
10         }
11 
12         /// <summary>
13         /// 读取指定节点的字符串
14         /// </summary>
15         /// <param name="keys"></param>
16         /// <returns></returns>
17         public static string ReadAppSettings(params string[] keys)
18         {
19             try
20             {
21                 if (keys.Any())
22                 {
23                     return _config[string.Join(":", keys)];
24                 }
25             }
26             catch
27             {
28                 return "";
29             }
30             return "";
31         }
32 
33         /// <summary>
34         /// 读取实体信息
35         /// </summary>
36         /// <typeparam name="T"></typeparam>
37         /// <param name="key"></param>
38         /// <returns></returns>
39         public static List<T> ReadAppSettings<T>(params string[] key)
40         {
41             List<T> list = new List<T>();
42             _config.Bind(string.Join(":", key), list);
43             return list;
44         }
45     }
46 }

 

appsettings.json

 1 {
 2   "Logging": {
 3     "LogLevel": {
 4       "Default": "Information",
 5       "Microsoft.AspNetCore": "Warning"
 6     }
 7   },
 8   "AllowedHosts": "*",
 9   "AppSettings": {
10     "Sqlstr": "datasrc=123.db"
11   }
12 }

Program.cs文件顶插入内容

using webc.Utils;

IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

CreateBuilder后插入

builder.Services.AddSingleton(new AppHelper(configuration));

 

调用

using webc.Utils;

public string show()
{
  return AppHelper.ReadAppSettings("AppSettings", "Sqlstr");
}

posted @ 2022-05-04 13:33  应世玉  阅读(93)  评论(0)    收藏  举报