以讀取預設的 appsetting.json 為例
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
}
}
建立存放 appsetting.json 的類別 MySetting.cs
public class MySetting
{
public Logging Logging { get; set; }
}
public class Logging
{
public LogLevel LogLevel { get; set; }
}
public class LogLevel
{
public string Default { get; set; }
}
在 Startup.cs 的 ConfigureServices 中註冊
public void ConfigureServices(IServiceCollection services)
{
services.Configure<mysetting>(Configuration);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
在 Controller 中使用 IOptions <mysetting>注入
public class HomeController : Controller
{
private IOptions<mysetting> myOption;
public HomeController(IOptions<mysetting> _option)
{
myOption = _option;
}
}
沒有留言:
張貼留言