我这里介绍的是使用IConfiguration来获取配置类信息
配置文件类信息(appsettings.json)
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Settings": {
"Port": "8000",
"IP": "http://localhost:5000",
},
"Url": "http://localhost:6000",
}
采用依赖注入的方式
第一种直接获取
首先在控制器中通过构造函数的方式引入IConfiguration
public class ExcelController : ControllerBase { private readonly IConfiguration _configuration; public ExcelController(IConfiguration configuration) { this._configuration = configuration; } }
在方法中我们就可以使用其获取配置类信息
//对于只有一个值的配置项,可以直接使用configuration["key"]来获取 var url = _configuration["Url"]; //对于有层级关系的配置项,可以使用GetSection方法来获取 var IP = _configuration.GetSection("Settings:IP").Value; var Port = _configuration.GetSection("Settings").GetSection("Port").Value;
至于为啥不用在容器中注入IConfiguration,因为
IConfiguration
是ASP.NET Core 基础设施的重要组成部分,它会在应用程序启动时被自动注册到依赖注入容器。- 无论你使用的是默认的 Web 应用模板,还是自定义的主机配置,
IConfiguration
都会作为单例服务被注册,其生命周期为应用程序的整个运行期间。
第二种采用配置绑定的方式
首先创建一个类,类名无所谓,但类里面的属性名要和配置类中的名字一样
public class A { public string IP { get; set; } public string Port { get; set; } }
在通过Bind()方法将配置类中同名的信息绑定在一块
A a = new A(); _configuration.Bind("Settings", a);
这里注意:配置类中的Url无法通过这样的方式进行绑定,因为它直接是一个字符串,不是一个对象了,如果也想通过配置绑定的方式,可以直接绑定整个配置类或者将Url改为对象的形式。
//1改为对象的形式 "UrlSettings": { // 改为对象 "Url": "http://localhost:6000" } ----------------------------------------------------------------------- //2创建一个类RootConfig public class RootConfig { public string Url { get; set; } public A Settings { get; set; } } //直接绑定整个配置 //注意这种直接绑定整个配置要类的属性为跟配置,如Url,Settings。如果像上面的绑定Settings, //如果直接采用_configuration.Bind(a)就不行,因为IP 和 Port 位于 Settings 节下,而非根配置。 RootConfig config = new RootConfig(); _configuration.Bind(config); // 访问方式 Console.WriteLine(config.Url); // "http://localhost:6000" Console.WriteLine(config.Settings.IP); // "http://localhost:5000"
直接使用IConfiguration创建对象的方式
IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var Url = configuration["Url"]; var Ip = configuration.GetSection("Settings:IP").Value; var Port = configuration.GetSection("Settings").GetSection("Port").Value;
以上采用依赖注入以及实例化对象的方式其实类似,下面那种只会加载"appsetting.json"的配置文件,而上面的那种使用的是应用程序全局配置实例,可以获取appsetting.json、appsettings.Environment.json、环境变量等所有配置值。