.net core读取配置文件

1、读取配置文件

首选随便定义一个实体类,比如这样的:

    public class WebConfig
    {
        public string PostLoan { get; set; }
    }

然后,在Startup文件注入配置文件的读取:

在ConfigureServices方法中添加一段代码:

services.Configure<WebConfig>(this.Configuration.GetSection("WebConfig"));

这样就可以了,不过需要配置文件中定义这个json格式,这样的:

{
  "WebConfig": {
    "PostLoan": "server=10.138.60.77;database=PostLoan;uid=sa;pwd=fyw554193;",
    "Loan": "kaiwaxasd"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

然后就完事了,在需要用到的地方用构造函数方式注入:

public HomeController(IOptions<WebConfig> config){}

然后config.Value就可以使用了,得到这个webconfig对象。

猜你喜欢

转载自my.oschina.net/uwith/blog/1809969