1,在 appsettings.json 中添加配置如:
"AppSetting": {
"connString": "Database=student_db;Data Source=localhost;User Id=root;Password=root;CharSet=utf8;port=3306"
}
2,建立存储 配置和读取配置的类
public class AppSettings
{
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;
}
}
3,在 站点 下的 Startup.cs 文件下 的 Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 方法中
调用 SetAppSetting 方法 设置 配置参数及其配置值 如:
Common.AppSettings.SetAppSetting(Configuration.GetSection("AppSetting"));
此处的配置节点 (AppSetting)要和 appsettings.json 中的节点一致
4,调用 AppSetting(string key) 方法 获取 配置参数
如 : private string connString =ConfigCommon.AppSettings.AppSetting("connString");