问题描述
我很熟悉将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?
推荐答案
您可以使用 Configuration.Bind(settings) ;
在 startup.cs
类中
您的设置类将类似于
public class AppSettings
{
public Dictionary<string, string> MobileConfigInfo
{
get;
set;
}
}
希望它会有所帮助!
这篇关于如何将appsetting.json部分加载到.NET Core中的Dictionary中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!