读取 appsettings.json

Appsettings.json 配置:

  个配置文件就是一个json文件,并且是严格的json文件,所有的属性都需要添加“”引号。下图是一个常规的代码示例:

{"UrlString": {
    //"Url": "http://27.151.14.174:8282/apiweb/?"
    "Url": "http://172.28.40.122:8080/apiweb/?"
  }
}

定义实体:

  获取Appsettings.json里面的信息需要定义对应的模型获取数据。如下图:

1
2
3
4
5
public class UrlString
    {
 
        public string Url { getset; }
    }

在StartUp时读取配置信息:

  在startup的ConfigureServices方法中读取配置信息。如下图:

复制代码
public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            //读取配置信息
            services.Configure<UrlString>(this.Configuration.GetSection("UrlString")); 
}
复制代码

实现类中调用实现业务,通过构造函数进入获取配置信息:

复制代码
public class DataCenterAppService : SanfuAppServiceBase, IDataCenterAppService{
    //定义累
     private readonly IOptions<UrlString> _appConfiguration;
      public DataCenterAppService(
          
            IOptions<UrlString> _appConfiguration
            )
        {
            this._appConfiguration = _appConfiguration;
        }
public string getStr(){
    return _appConfiguration.Value.url;
}

}
复制代码
原文地址:https://www.cnblogs.com/Jeely/p/10959378.html