抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

介绍

之前的.Net framework 程序一般使用 App.config 作为配置文件,不过微软在发布跨平台的 .Net core 后开始使用 appsettings.json 作为配置文件,下面就在 .Net 6 控制台应用中创建一个通用类方法来读取 appsettings.json 配置文件。

创建通用读取类

安装包:

1
2
3
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class ConfigHelper
{
public static ConfigHelper _Instance;
private static IConfigurationRoot _ConfigurationRoot;
private static readonly object _ThisLock = new();

public ConfigHelper()
{
_ConfigurationRoot=new ConfigurationBuilder()
.SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))
.AddJsonFile("appsettings.json",optional:false)
.Build();
}
public static ConfigHelper Instance
{
get
{
lock (_ThisLock)
{
_Instance ??= new ConfigHelper();
return _Instance;
}
}
}

/// <summary>
/// Get ConnectionStrings
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public string? GetConnectionString(string key,string? defaultValue =null)
{
string result = _ConfigurationRoot.GetConnectionString(key);
if(result == null)
return defaultValue;
return result;
}

/// <summary>
/// Get appsettings section
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public T GetAppSettings<T>(string key, T defaultValue)
{
IConfigurationSection configSection = _ConfigurationRoot.GetSection(key);
if (configSection.Value != null)
{
return (T)Convert.ChangeType(configSection.Value, typeof(T));
}
return defaultValue;
}
}

测试

创建 appsettings.json 文件

1
2
3
4
5
6
7
8
9
10
{
"ConnectionStrings": {
"mongodb": "mongodb://root:pwd@localhost:27017/mydb"
},
"Logging": {
"LogLevel": {
"Default": "Information"
}
}
}
  1. 读取数据库连接字符串:

    1
    ConfigHelper.Instance.GetConnectionString("mongodb")
  2. 读取配置节点

    1
    ConfigHelper.Instance.GetAppSettings("Logging:LogLevel:Default","")

评论