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

2021/9/26 12:10:55

本文主要是介绍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"];



这篇关于asp.net core 读取配置文件之-Configuration的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程