asp.net core 读取配置文件之-Configuration

 private readonly IConfiguration _iConfiguration = null;
        public ConfigurationController(IConfiguration configuration)
        {
            this._iConfiguration = configuration;
        }

appsettings.json读取方式

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  
  "AllowedHosts": "*",
  "Today": "0624",
  "ConnectionStrings": {
    "JDDbConnection": "Server=PC;Database=advanced11;User id=sa;password=Sasa123",
    "Write": "Data Source=PC; Database=Customers; User ID=sa; Password=Sasa123; MultipleActiveResultSets=True",
    "Read": [
      "Data Source=.; Database=Customers_New1; User ID=sa; Password=Passw0rd; MultipleActiveResultSets=True",
      "Data Source=PC; Database=Customers_New2; User ID=sa; Password=Passw0rd; MultipleActiveResultSets=True",
      "Data Source=.; Database=Customers_New3; User ID=sa; Password=Passw0rd; MultipleActiveResultSets=True"
    ]
  },
  "RabbitMQOptions": {
    "HostName": "192.168.0.118",
    "UserName": "guest",
    "Password": "guest"
  }
}

方式1:简单key 读取
 

  string AllowedHosts = this._iConfiguration["AllowedHosts"];

 string writeConn = this._iConfiguration["ConnectionStrings:Write"];
 string readConn0 = this._iConfiguration["ConnectionStrings:Read:0"];//某一个值
  string[] _SqlConnectionStringRead = this._iConfiguration.GetSection("ConnectionStrings").GetSection("Read").GetChildren().Select(s => s.Value).ToArray();//数组

 方式2:命令行读取方式

dotnet run --urls="http://*:5555" ip="127.0.0.1" /port=5555 ConnectionStrings:Write=CommandLineArgument

 string urls = this._iConfiguration["urls"];
 string ip = this._iConfiguration["ip"];
 string port = this._iConfiguration["port"];
string writeConn = this._iConfiguration["ConnectionStrings:Write"];

方式3:build 与get方式 直接将读取app.json里的值存储到某一对象

RabbitMQOptions rabbitMQOptions1 = new RabbitMQOptions();
   this._iConfiguration.GetSection("RabbitMQOptions").Bind(rabbitMQOptions1);
            
 RabbitMQOptions rabbitMQOptions2 = this._iConfiguration.GetSection("RabbitMQOptions").Get<RabbitMQOptions>();

除此之外还支持内存读取,读取方式和以上方式没什么区别

内存设置Program--》ConfigureAppConfiguration设置:

 var memoryConfig = new Dictionary<string, string>
                 {
                    {"TodayMemory", "0624-Memory"},
                    {"RabbitMQOptions:HostName", "192.168.0.118-Memory"},
                     {"RabbitMQOptions:UserName", "guest-Memory"},
                      {"RabbitMQOptions:Password", "guest-Memory"}
                 };
                 configurationBuilder.AddInMemoryCollection(memoryConfig);

读取内存方式

string HostName = this._iConfiguration["RabbitMQOptions:HostName"];
string TodayMemory = this._iConfiguration["TodayMemory"];

上一篇:ACM-ICPC 2018 徐州赛区网络预赛 A.Hard to prepare 【规律递推】


下一篇:浅析Asp.Net Core框架IConfiguration配置