.net core读取配置文件
先添加这两个开发包:
这是配置文件;
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "name": { "name": "testConfig" } }
代码(.net core 6):
ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);//, reloadonChange: false); IConfigurationRoot config = configBuilder.Build(); //string name = config["name"]; //Console.WriteLine($"name={name}"); string proxyAddress = config.GetSection("Logging:LogLevel:Default").Value; Console.WriteLine($"Address: {proxyAddress}");
控制台输出:
-----------------------------------------------------------------------------------------------
.net 8.0 :
IConfiguration config = new ConfigurationBuilder() //.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) //.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true) //.AddEnvironmentVariables() .Build() ; var connStr = config.GetSection("ConnectionStrings:conn").Value;