C# 如何将appsetting.json节加载到.NET Core中的字典中?
我熟悉将appsettings.json节加载到.NET Core startup.cs中的强类型对象中。例如:C# 如何将appsetting.json节加载到.NET Core中的字典中?,c#,asp.net-core,.net-core,C#,Asp.net Core,.net Core,我熟悉将appsettings.json节加载到.NET Core startup.cs中的强类型对象中。例如: public class CustomSection { public int A {get;set;} public int B {get;set;} } //In Startup.cs services.Configure<CustomSection>(Configuration.GetSection("CustomSection")); //Inj
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;
}
是否有方法将此数据加载到MobileConfigInfo字典对象中,然后使用IOOptions模式将MobileConfigInfo注入控制器?您可以使用
配置.Bind(设置)代码>在startup.cs
类中
您的设置类将是
public class AppSettings
{
public Dictionary<string, string> MobileConfigInfo
{
get;
set;
}
}
公共类AppSettings
{
公共词典MobileConfigInfo
{
得到;
设置
}
}
希望有帮助 对于希望将其转换为词典的其他人
appsettings.json中的示例部分
以下代码应放在启动文件>配置服务方法中:
public static Dictionary<string, object> MailSettings { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
//ConfigureServices code......
MailSettings = Configuration.GetSection("MailSettings").GetChildren()
.ToDictionary(x => x.Key, x => x.Value);
}
一个缺点是,所有值都将作为字符串检索,如果尝试任何其他类型,值将为空。使用此结构格式:
"MobileConfigInfo": {
"Values": {
"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."
}
}
使您的设置类如下所示:
public class CustomSection
{
public Dictionary<string, string> Values {get;set;}
}
公共类自定义部分
{
公共字典值{get;set;}
}
那就这样做吧
services.Configure<CustomSection>((settings) =>
{
Configuration.GetSection("MobileConfigInfo").Bind(settings);
});
services.Configure((设置)=>
{
Configuration.GetSection(“MobileConfigInfo”).Bind(设置);
});
对于简单(可能是微服务)应用程序,您只需将其添加为单例字典
,然后将其注入到需要的任何地方:
var mobileConfig = Configuration.GetSection("MobileConfigInfo")
.GetChildren().ToDictionary(x => x.Key, x => x.Value);
services.AddSingleton(mobileConfig);
以及用法:
public class MyDependantClass
{
private readonly Dictionary<string, string> _mobileConfig;
public MyDependantClass(Dictionary<string, string> mobileConfig)
{
_mobileConfig = mobileConfig;
}
// Use your mobile config here
}
公共类MyDependent类
{
专用只读词典mobileConfig;
公共MyDependent类(字典mobileConfig)
{
_mobileConfig=mobileConfig;
}
//在这里使用您的移动配置
}
作为ASP.Net Core 2.1中更复杂绑定的示例;根据,我发现使用ConfigurationBuilder
.Get()
方法要容易得多
ASP.NET Core 1.1及更高版本可以使用Get,它可以处理整个部分。Get比使用Bind更方便
我在启动
方法中绑定了配置
private Config Config { get; }
public Startup(IConfiguration Configuration)
{
Config = Configuration.Get<Config>();
}
在该配置结构中:
[DataContract]
public class Config
{
[DataMember]
public Dictionary<string, string> ConnectionStrings { get; set; }
[DataMember]
public PluginCollection Plugins { get; set; }
}
[DataContract]
public class PluginCollection
{
[DataMember]
public Dictionary<string, SmsConfiguration> Sms { get; set; }
[DataMember]
public Dictionary<string, EmailConfiguration> Smtp { get; set; }
}
[DataContract]
public class SmsConfiguration
{
[DataMember]
public string Scheme { get; set; }
[DataMember]
public string Host { get; set; }
[DataMember]
public int Port { get; set; }
[DataMember]
public string Path { get; set; }
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string Source { get; set; }
[DataMember]
public bool DeliveryReporting { get; set; }
[DataMember]
public string Encoding { get; set; }
}
[DataContract]
public class EmailConfiguration
{
[DataMember]
public string Scheme { get; set; }
[DataMember]
public string Host { get; set; }
[DataMember]
public int Port { get; set; }
[DataMember]
public string Path { get; set; }
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string DefaultSender { get; set; }
[DataMember]
public bool EnableSsl { get; set; }
}
[DataContract]
公共类配置
{
[数据成员]
公共字典连接字符串{get;set;}
[数据成员]
公共插件集合插件{get;set;}
}
[数据合同]
公共类插件集合
{
[数据成员]
公共字典Sms{get;set;}
[数据成员]
公共字典Smtp{get;set;}
}
[数据合同]
公共类SMS配置
{
[数据成员]
公共字符串方案{get;set;}
[数据成员]
公共字符串主机{get;set;}
[数据成员]
公共int端口{get;set;}
[数据成员]
公共字符串路径{get;set;}
[数据成员]
公共字符串用户名{get;set;}
[数据成员]
公共字符串密码{get;set;}
[数据成员]
公共字符串源{get;set;}
[数据成员]
公共布尔交付报告{get;set;}
[数据成员]
公共字符串编码{get;set;}
}
[数据合同]
公共类电子邮件配置
{
[数据成员]
公共字符串方案{get;set;}
[数据成员]
公共字符串主机{get;set;}
[数据成员]
公共int端口{get;set;}
[数据成员]
公共字符串路径{get;set;}
[数据成员]
公共字符串用户名{get;set;}
[数据成员]
公共字符串密码{get;set;}
[数据成员]
公共字符串DefaultSender{get;set;}
[数据成员]
公共布尔启用SSL{get;set;}
}
我使用以下方法:
appsettings.json:
"services": {
"user-service": "http://user-service:5000/",
"app-service": "http://app-service:5000/"
}
{
"myConfig": {
"foo": "bar",
"myMappings": {
"key1": "value1",
"key2": "value2"
}
}
}
startup.cs:
services.Configure<Dictionary<string, string>>(Configuration.GetSection("services"));
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyConfig>(configuration.GetSection("myConfig"));
services.Configure(Configuration.GetSection(“services”);
用法:
private readonly Dictionary<string, string> _services;
public YourConstructor(IOptions<Dictionary<string, string>> servicesAccessor)
{
_services = servicesAccessor.Value;
}
private readonly Dictionary\u服务;
公共构造函数(IOptions服务访问器)
{
_services=servicesAccessor.Value;
}
我相信您可以使用以下代码:
var config = Configuration.GetSection("MobileConfigInfo").Get<Dictionary<string, string>>();
var config=Configuration.GetSection(“MobileConfigInfo”).Get();
到目前为止,最简单的方法是定义要从要支持的字典类型继承的配置类
public class MobileConfigInfo:Dictionary<string, string>{
}
公共类MobileConfigInfo:字典{
}
然后,您的启动和依赖项注入支持将与任何其他配置类型完全相同。对我(ASP.NET Core 3.0)唯一有效的方法是将以下内容添加到startup.cs的ConfigureServices
方法中:
services.Configure<Dictionary<string, string>>(dict => Configuration
.GetSection("MySectionName")
.GetChildren()
.ToList()
.ForEach(c => dict[c.Key] = c.Value));
services.Configure(dict=>Configuration
.GetSection(“MySectionName”)
.GetChildren()
托利斯先生()
.ForEach(c=>dict[c.Key]=c.Value));
在.NET Core 3.1中,您可以执行以下操作
appsettings.json:
"services": {
"user-service": "http://user-service:5000/",
"app-service": "http://app-service:5000/"
}
{
"myConfig": {
"foo": "bar",
"myMappings": {
"key1": "value1",
"key2": "value2"
}
}
}
配置模型
MyConfig.cs
public class MyConfig
{
public string Foo { get; set; }
public Dictionary<string, string> MyMappings { get; set; }
}
公共类MyConfig
{
公共字符串Foo{get;set;}
公共字典MyMappings{get;set;}
}
Startup.cs:
services.Configure<Dictionary<string, string>>(Configuration.GetSection("services"));
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyConfig>(configuration.GetSection("myConfig"));
public void配置服务(IServiceCollection服务)
{
services.Configure(configuration.GetSection(“myConfig”);
使用以下选项初始化:
public class OptionsUsingClass
{
public OptionsUsingClass(IOptions<MyConfig> myConfigOptions)
{
// Be wary of nulls in real code.
var myConfig = myConfigOptions.Value;
// Examples with the above data.
myConfig.Foo.Should().Be("bar");
myConfig.MyMappings["key1"].Should().Be("value1");
myConfig.MyMappings["key2"].Should().Be("value2");
}
公共类选项使用类
{
公共选项使用类(IOOptions myConfigOptions)
{
//要小心实际代码中的空值。
var myConfig=myConfigOptions.Value;
//以上述数据为例。
myConfig.Foo.Should().Be(“bar”);
myConfig.MyMappings[“key1”].Should().Be(“value1”);
myConfig.MyMappings[“key2”].Should().Be(“value2”);
}
这就是我使用appsettings.json字典映射的方式。您可以随时使用:
appsettings.json:
{
"MobileConfigInfo": {
"a": "x",
"b": "y",
"c": "z"
}
}
代码中的某个地方:(不要忘记将IConfiguration依赖项添加到类构造函数)
var yourDictionary=\u configuration.GetSection(“MobileConfigInfo”)
.Get();
Hmmm这个问题不是关于ASP.NET Core而不是.NET Core吗?有点误导性。不要错过文章最下面的杰里米·拉克曼的答案。非常干净,非常简单。这对我很有效。如果字典在sec的更深处,也很有效
var yourDictionary = _configuration.GetSection("MobileConfigInfo")
.Get<IDictionary<string, string>>();