您可以为您的配置创建一个映射类,如下所示:
public class ConfigSettings
{
public string ConfigSetting1 { get; set; }
public string ConfigSetting2 { get; set; }
public string ConfigSetting3 { get; set; }
public SubConfigSettings1 SubConfigSettings1 { get; set; }
}
public class SubConfigSettings1
{
public string SubConfigSetting1 { get; set; }
public string SubConfigSetting2 { get; set; }
}
并使用它们来获取它们,
var setting = Configuration.Get<ConfigSettings>();
编辑:
如果你有这个钢趾配置
{
"spring": {
"cloud": {
"config": {
"uri": "http://localhost:8888"
}
}
},
"Logging": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
},
"Console": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
}
您可以像这样定义 ConfigSettings 类。
public class ConfigSettings
{
public Spring spring { get; set; }
public Logging Logging { get; set; }
}
public class Spring
{
public Cloud cloud { get; set; }
}
public class Cloud
{
public Config config { get; set; }
}
public class Config
{
public string uri { get; set; }
}
public class Logging
{
public bool IncludeScopes { get; set; }
public Loglevel LogLevel { get; set; }
public Console Console { get; set; }
}
public class Console
{
public Loglevel LogLevel { get; set; }
}
public class Loglevel
{
public string Default { get; set; }
public string System { get; set; }
public string Microsoft { get; set; }
}
并像这样使用。
services.Configure<ConfigSettings>(Configuration);
并使用以下内容访问 uri 部分,例如。
var settings = Configuration.Get<ConfigSettings>();
string springCloudConfigUri = settings.spring.cloud.config.uri;
这里的配置是 IConfiguration