{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"AppSettings": {
"SqlServerConnection": "Server=127.0.0.1;Database=demo;User ID=sa;Password=sa;",
"RedisCaching": {
"Enabled": true,
"ConnectionString": "127.0.0.1:6379"
}
}
}
1、初始化注入方式
Startup.cs下ConfigureServices方法:
services.AddOptions();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
public class AppSettings
{
public RedisCaching RedisCaching { get; set; }
} public class RedisCaching
{
/// <summary>
/// 是否启用
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// 链接信息
/// </summary>
public string ConnectionString { get; set; }
}
然后在控制器中调用:
public readonly IOptions<AppSettings> Setting;
public HomeController(IOptions<AppSettings> setting)
{
Setting = setting;
} public IActionResult Index()
{
var s = Setting.Value.RedisCaching.ConnectionString;
ViewData["abc"] = s;
return View();
}
2、读取appsettings.json方式
(此方法如在单独的类库中需引用Microsoft.Extensions.Options.ConfigurationExtensions、Microsoft.Extensions.Configuration.FileExtensions、Microsoft.Extensions.Configuration.Json)
1)先设置appsettings.json文件复制到根目录.右键appsettings.json 高级 复制到输出目录中选“始终复制”.
2)
public T Get<T>(string key)
{
IConfiguration config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true).Build(); return config.GetSection(key).Get<T>();
}
public IActionResult Index()
{
var s = new GetAppSetting().Get<string>("AppSettings:SqlServerConnection");
ViewData["abc"] = s;
return View();
}
第一种方法在别的类库中也可调用,比较方便,刚做core项目,用第一种方法时类库中不好调用,查了半天用第二种就可以了。