读取 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里面的信息需要定义对应的模型获取数据。如下图:

public class UrlString
    {

        public string Url { get; set; }
    }

在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;
}

}

  

猜你喜欢

转载自www.cnblogs.com/yhnx/p/9174523.html