1、在Startup.cs文件中注入,ConfigureServices方法
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
AppSetting.json文件
"MyConfig": { "ResVersion": "1.0.2 Beta" },
自定义类
public class MyConfig { public string ResVersion { get; set; } }
使用
public class ValuesController : Controller { private readonly MyConfig _config; public ValuesController(IOptions<MyConfig> op) { _config = op.Value; } }
2、读取指定节点下节点值。Nuget引入Microsoft.Extensitions.Configuration。
自定义AppSettingHelper.cs。
public class AppSettingsHelper { private static IConfigurationSection appSections = null; public static string AppSetting(string key) { string str = ""; if (appSections.GetSection(key) != null) { str = appSections.GetSection(key).Value; } return str; } public static void SetAppSetting(IConfigurationSection section) { appSections = section; } }
在Startup.cs中ConfigureServices引入
AppSettingsHelper.SetAppSetting(Configuration.GetSection("AppSettings"));
AppSetting.json文件,只限AppSettings下一级节点
"AppSettings": { "Url": "test" }
使用
var url = AppSettingsHelper.AppSetting("Url");
3、不通过依赖注入形式。自定义AppSettingHelper.cs类。
Nuget引入Microsoft.Extensitions.Configuration和Microsoft.Extensitions.Configuration.Json
public class AppSettingsHelper { public static IConfiguration Configuration { get; set; } static AppSettingsHelper() { //ReloadOnChange = true 当appsettings.json被修改时重新加载 Configuration = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }) .Build(); } public static string SMSSign { get { return Configuration["SMS:SMSSign"]; } } }
AppSetting.json配置文件
"SMS": { "SMSSign": "测试" },
使用直接调用 AppSettingHelper.SMSSign;