码迷,mamicode.com
首页 > Web开发 > 详细

NetCore配置文件读取

时间:2019-12-23 13:35:20      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:private   max   core   rabl   default   get   ret   war   logging   

配置文件如下

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "WebSetting": {
    "WebName": "ASP.NET Core",
    "Title": "Hello Title",
    "Behavior": {
      "IsCheckIp": true,
      "MaxConnection": 300
     }
   }
}

方法一、键读取

首先,在类构造函数注入  IConfiguration,例如:

 public IConfiguration Configuration { get; }
 public ValuesController(IConfiguration configuration)
 {
     Configuration = configuration;
 }

然后就可以在该类任何方法读取:

[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
   var title = Configuration["WebSetting:Title"];
   var isCheckIp = Configuration["WebSetting:Behavior:IsCheckIp"];
   return new string[] { title, isCheckIp };
}

方法二、绑定读取

首先,还是类构造函数注入ICofiguration

public IConfiguration Configuration { get; }
public ValuesController(IConfiguration configuration)
{
    Configuration = configuration;
}

然后,创建配置项结构对应的配置模型

public class Behavior
{
    public bool IsCheckIp { get; set; }
    public int MaxConnection { get; set; }
}

public class WebSetting
{
     public string WebName { get; set; }
     public string Title { get; set; }
     public Behavior Behavior { get; set; }
}

最后如下方式读取配置

[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
   var webSetting = new WebSetting();
   Configuration.GetSection("WebSetting").Bind(webSetting);
   var webName = webSetting.WebName;
   var isCheckIp = webSetting.Behavior.IsCheckIp;
   return new string[] { webName, isCheckIp.ToString() };
}

方法三、注册读取

首先,创建配置项结构对应的配置模型

public class Behavior
{
    public bool IsCheckIp { get; set; }
    public int MaxConnection { get; set; }
}

public class WebSetting
{
     public string WebName { get; set; }
     public string Title { get; set; }
     public Behavior Behavior { get; set; }
}

然后,在 ConfigureServices 方法中注册

 public void ConfigureServices(IServiceCollection services)
{
          
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    //注册配置
    services.Configure<WebSetting>(Configuration.GetSection("WebSetting"));
}

最后读取配置:在读取配置的类构造函数注入IOptions,就可以在该类任何位置读取配置如下

1、构造函数注入读取

private IOptions<WebSetting> webSettingOption;
//构造函数
public ValuesController(IOptions<WebSetting> _webSettingOption)
{
    webSettingOption = _webSettingOption;
}

       
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
     var webName = webSettingOption.Value.WebName;
     var isCheckIp = webSettingOption.Value.Behavior.IsCheckIp;
     return new string[] { webName, isCheckIp.ToString() };
}

NetCore配置文件读取

标签:private   max   core   rabl   default   get   ret   war   logging   

原文地址:https://www.cnblogs.com/come-on-come-on/p/12083016.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!