使用C#的接口继承特性,我们可以将接口内的配置接口嵌套到其它接口中,在appsettings.json中以路径的形式调用。
示例代码如下:
public interface ILoggingSettings { string LogLevel { get; set; } }
public interface IAppSettings : ILoggingSettings { string ConnectionString { get; set; } int Timeout { get; set; } }
在appsettings.json中,我们可以通过以下方式访问配置:
{ "AppSettings": { "LogLevel": "Debug", "ConnectionString": "server=myServerAddress;database=myDataBase;uid=myUsername;password=myPassword;", "Timeout": 30 } }
var appSettings = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build()
.GetSection("AppSettings")
.Get
此时,我们就可以通过appSettings变量来访问appsettings.json文件中的配置了。