本文主要是介绍.net 6.0如何直接读取appsetting.json配置文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
现在有一个appsetting.json配置文件,里面有个setting下的url地址,需要读取,如下:
{"Logging": {"LogLevel": {"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"}},"Setting": {"Url": "127.0.0.1:8080"}
}
不添加任何类,直接读取appsetting.json的两种方法:
1.利用ConfigurationBuilder
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);IConfigurationRoot configuration = builder.Build();var value = configuration["Setting:Url"];Console.log($"Url地址是: {value}");
2.利用IConfiguration,注入IConfiguration
[ApiController]
[Route("[controller]/[action]")]
public class TestController: ControllerBase
{public IConfiguration _configuration { get; set; }public TestController(IConfiguration configuration){_configuration = configuration;}/// <summary>/// 利用IConfiguration直接读取单个值的3个方法/// </summary>[HttpGet, HttpPost]public void GetConfiguration(){var url = _configuration["Setting:Url"]; // http://127.0.0.1:8080/var url2 = _configuration.GetValue<string>("Setting:Url"); // http://127.0.0.1:8080/var url3 = _configuration.GetSection("Setting").GetSection("Url").Value; // http://127.0.0.1:8080/}
}
这篇关于.net 6.0如何直接读取appsetting.json配置文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!