.net core 读取 appsetting.json
文件 appsetting.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "User ID=sa;Password=123@abcd;Initial Catalog=CommonPower;Data Source=AFOCL-703281007\\SQLEXPRESS",
"ProviderName": "SqlServer" //驱动提供者(数据库品牌) //sqlserver、oracle、mysql
},
//"AppSettings": {
// "ConnectionString": "Server=10.0.0.1;database=HasngCadreFile;uid=sa;pwd=123-abc", //数据库连接字符串
// //"ConnectionString": "Server=192.168.1.250;database=HasngCadreFile;uid=sa;pwd=123-abc", //数据库连接字符串
// "ProviderName": "SqlServer" //驱动提供者(数据库品牌) //sqlserver、oracle、mysql
//},
"RedisConfig": {
"Connection": "10.0.0.1:6379,abortConnect=false,password=123456"
//"Connection": "192.168.1.250:6379,abortConnect=false,password=123456"
},
"ServiceAddress": {
"Address": "http://10.0.0.1:5052",
//"Address": "http://192.168.1.250:5052",
"IsOpenOnlyUser": false, //一个账号多地点登陆 true,false
"PageTimeOut": 20 //数字 (分钟)
}
}
2.读取配置文件方式
DbHelper.ConnectionString = Configuration.GetConnectionString("DefaultConnection"); DbHelper.DatabaseTypeEnumParse(Configuration.GetConnectionString("ProviderName")); //DbHelper.ConnectionString = Configuration.GetSection("AppSettings").GetSection("ConnectionString").Value; //DbHelper.DatabaseTypeEnumParse(Configuration.GetSection("AppSettings").GetSection("ProviderName").Value); DbHelper.DbParmChar = DbFactory.CreateDbParmCharacter(); //配置缓存信息 CacheHelper.ConnectionString = Configuration.GetSection("RedisConfig").GetSection("Connection").Value; //读取守护程序地址 GlobalStatus.Address = Configuration.GetSection("ServiceAddress").GetSection("Address").Value; //读取页面过期时间(分钟) GlobalStatus.PageTimeOut = Convert.ToInt32(Configuration.GetSection("ServiceAddress").GetSection("PageTimeOut").Value); //读取是否开启单用户登陆认证 GlobalStatus.IsOpenOnlyUser = Convert.ToBoolean(Configuration.GetSection("ServiceAddress").GetSection("IsOpenOnlyUser").Value);
3.对象方式读取配置文件节点
public class AppSettings { /// <summary> /// 连接字符串 /// </summary> public string ConnectionString { get; set; } /// <summary> /// 驱动提供者 /// </summary> public string ProviderName { get; set; } public string Connection { get; set; } public string Address { get; set; } public bool IsOpenOnlyUser { get; set; } public string PageTimeOut { get; set; } }
startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddSingleton(Configuration);
//关键点,配置映射文件
services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); services.AddMvc();
}
controller.cs
public class AccountController : Controller { AppSettings _op; public AccountController(IOptions<AppSettings> op) { _op = op.Value; } }