现在有一个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/}
}