Bha*_*anu 3 c# .net-core asp.net-core
我正在使用 .NET Core 5.0。我在 appsettings.json 文件中有以下部分。
"Policies": [
{
"name": "ApproverPolicy",
"description": "ApproverPolicy",
"rules": [
{
"name": "abc@gmail.com",
"description": "abc@gmail.com"
},
{
"name": "def@gmail.com",
"description": "def@gmail.com"
}
]
},
{
"name": "RegionPolicy",
"description": "RegionPolicy",
"rules": [
{
"name": "East US",
"description": "East US"
},
{
"name": "North Europe",
"description": "North Europe"
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
我定义了以下 C# 类。
public class Policy : PolicyDefinition
{
public IList<Rule> Rules { get; set; }
}
public class PolicyDefinition
{
public string Name { get; set; }
public string Description { get; set; }
}
public class Rule
{
public string Name { get; set; }
public string Description { get; set; }
public RuleStatus Status { get; set; }
public DateTime UpdatedAt { get; set; }
public string UpdatedBy { get; set; }
}
public enum RuleStatus
{
Undefined = 0,
Blocked = 1,
Approved = 2,
Rejected = 4,
Unknown = 8
}
Run Code Online (Sandbox Code Playgroud)
我正在使用以下代码从 appsettings.json 文件中读取策略部分。Name 和 Description 属性按预期填充,但“Rules”属性为 NULL。正确填充规则属性需要哪些更改?非常感激你的帮助。
_configuration.GetSection("Policies")
.GetChildren()
.ToList()
.Select(x => new Policy
{
Name = x.GetValue<string>("name"),
Description = x.GetValue<string>("description"),
Rules = x.GetValue<IList<Rule>>("rules")
}).ToList();
Run Code Online (Sandbox Code Playgroud)
以下代码适用于这种情况。感谢所有的帮助。
_configuration.GetSection("Policies").Get<List<Policy>>().ToList();
Run Code Online (Sandbox Code Playgroud)
声明一个与您的 appsettings 结构相匹配的类会更容易。然后你可以在启动时设置它们并使用 IOptions 将它注入到类中。
用于启动
var appSettingsSection = Configuration.GetSection("Policies");
services.Configure<List<Policy>>(appSettingsSection);
var appSettings = appSettingsSection.Get<List<Policy>>();
Run Code Online (Sandbox Code Playgroud)
然后当你注射
public SomeClass(IOptions<List<Policy>> options){
var policies = options.Value;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
796 次 |
最近记录: |