AppsettingsHelp.cs
2.13 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Options;
namespace Hh.Mes.Common.config
{
/// <summary>
/// AppsettingsHelp json操作类
/// </summary>
public class AppsettingsHelp
{
public T GetAppsettings<T>(string key) where T : class, new()
{
//https://www.cnblogs.com/zhouzangood/articles/2987088.html
string keyDir = AppDomain.CurrentDomain.BaseDirectory ;
IConfiguration config = new ConfigurationBuilder()
.SetBasePath(keyDir)
.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
.Build();
var appconfig = new ServiceCollection()
.AddOptions()
.Configure<T>(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<T>>()
.Value;
return appconfig;
}
public IConfigurationRoot GetAppsettings()
{
string keyDir = AppDomain.CurrentDomain.BaseDirectory;
var builder = new ConfigurationBuilder()
.SetBasePath(keyDir)
.AddJsonFile("appsettings.json");
return builder.Build();
}
}
public class AppSettings
{
private static IConfigurationSection appSection = null;
/// <summary>
/// 设置配置文件 Startup 注入
/// </summary>
/// <param name="section"></param>
public static void SetAppSetting(IConfigurationSection section)
{
appSection = section;
}
/// <summary>
/// 获取配置文件 AppSettings.GetAppSeting("xxx")
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetAppSeting(string key)
{
return appSection.GetSection(key) != null ? appSection.GetSection(key).Value : "";
}
}
}