如何将 appsetting.json 部分加载到 .NET Core 中的 Dictionary 中? [英] How to load appsetting.json section into Dictionary in .NET Core?
问题描述
我熟悉将 appsettings.json 部分加载到 .NET Core startup.cs 中的强类型对象中.例如:
I am familiar w/ loading an appsettings.json section into a strongly typed object in .NET Core startup.cs. For example:
public class CustomSection
{
public int A {get;set;}
public int B {get;set;}
}
//In Startup.cs
services.Configure<CustomSection>(Configuration.GetSection("CustomSection"));
//Inject an IOptions instance
public HomeController(IOptions<CustomSection> options)
{
var settings = options.Value;
}
我有一个 appsettings.json 部分,其键/值对的数量和名称会随着时间的推移而变化.因此,在类中硬编码属性名称是不切实际的,因为新的键/值对需要在类中更改代码.一些键/值对的小样本:
I have an appsettings.json section who's key/value pairs will vary in number and name over time. Therefore, it's not practical to hard code property names in a class since new key/value pairs would require a code change in the class. A small sample of some key/value pairs:
"MobileConfigInfo": {
"appointment-confirmed": "We've booked your appointment. See you soon!",
"appointments-book": "New Appointment",
"appointments-null": "We could not locate any upcoming appointments for you.",
"availability-null": "Sorry, there are no available times on this date. Please try another."
}
有没有办法将这些数据加载到 MobileConfigInfo Dictionary 对象中,然后使用 IOptions 模式将 MobileConfigInfo 注入控制器?
Is there a way to load this data into a MobileConfigInfo Dictionary object and then use the IOptions pattern to inject MobileConfigInfo into a controller?
推荐答案
你可以在startup.cs
类
你的设置类会像
public class AppSettings
{
public Dictionary<string, string> MobileConfigInfo
{
get;
set;
}
}
希望能帮到你!
这篇关于如何将 appsetting.json 部分加载到 .NET Core 中的 Dictionary 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!