如何在.NET Core中将appsetting.json部分加载到Dictionary中?

Chr*_*isP 32 c# .net-core asp.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"));

//Inject an IOptions instance
public HomeController(IOptions<CustomSection> options) 
{
    var settings = options.Value;
}
Run Code Online (Sandbox Code Playgroud)

我有一个appsettings.json部分,其键/值对随着时间的推移会在数量和名称上有所不同.因此,对类中的属性名称进行硬编码是不切实际的,因为新的键/值对需要在类中进行代码更改.一些键/值对的小样本:

"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."
}
Run Code Online (Sandbox Code Playgroud)

有没有办法将此数据加载到MobileConfigInfo Dictionary对象中,然后使用IOptions模式将MobileConfigInfo注入控制器?

Hun*_*Cao 23

你可以Configuration.Bind(settings);startup.cs课堂上使用

你的设置类就像

public class AppSettings
{
    public Dictionary<string, string> MobileConfigInfo
    {
        get;
        set;
    }
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!

  • 这不适用于具有“Dictionary&lt;string, string&gt;”属性的类。Bind 方法在运行时失败,并显示:“System.InvalidOperationException:‘无法创建类型‘System.String’的实例,因为它缺少公共无参数构造函数。” (4认同)

cod*_*de5 22

使用这种结构格式:

"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."
 }
}
Run Code Online (Sandbox Code Playgroud)

使您的设置类看起来像这样:

public class CustomSection 
{
   public Dictionary<string, string> Values {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

然后这样做

services.Configure<CustomSection>((settings) =>
{
     Configuration.GetSection("MobileConfigInfo").Bind(settings);
});
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用。如果字典位于部分配置的更深处,则也可以使用绑定调用。 (2认同)
  • 除此之外,只要您使用“Microsoft.Extensions.Options”中的“services.AddOptions()”,就不需要使用“Bind”。这就足够了: `services.Configure&lt;CustomSection&gt;(Configuration.GetSection("MobileConfigInfo"));` (2认同)

Jer*_*man 20

到目前为止,最简单的方法是定义您的配置类以从您想要支持的 Dictionary 类型继承。

public class MobileConfigInfo:Dictionary<string, string>{
}
Run Code Online (Sandbox Code Playgroud)

那么您的启动和依赖注入支持将与任何其他配置类型完全相同。


Amr*_*mro 18

对于想要将其转换为字典的其他人,

appsettings.json中的示例部分

"MailSettings": {
    "Server": "http://mail.mydomain.com"        
    "Port": "25",
    "From": "info@mydomain.com"
 }
Run Code Online (Sandbox Code Playgroud)

以下代码应放在Startup文件> ConfigureServices方法中:

public static Dictionary<string, object> MailSettings { get; private set; }

public void ConfigureServices(IServiceCollection services)
{
    //ConfigureServices code......

    MailSettings = 
        Configuration.GetSection("MailSettings").GetChildren()
        .Select(item => new KeyValuePair<string, string>(item.Key, item.Value))
        .ToDictionary(x => x.Key, x => x.Value);
}
Run Code Online (Sandbox Code Playgroud)

现在您可以从以下任何地方访问字典:

string mailServer = Startup.MailSettings["Server"];
Run Code Online (Sandbox Code Playgroud)

一个缺点是所有值都将作为字符串检索,如果您尝试任何其他类型,该值将为null.

  • 你不需要`.Select(item => new KeyValuePair <string,string>(item.Key,item.Value))`part.你可以调用`GetChildren().ToDictionary(x => x.Key,x => x.Value)`. (3认同)

mac*_*pak 10

我相信您可以使用以下代码:

var config =  Configuration.GetSection("MobileConfigInfo").Get<Dictionary<string, string>>(); 
Run Code Online (Sandbox Code Playgroud)


小智 9

我用的是下面的方式:

\n\n

应用程序设置.json:

\n\n
  "services": {\n      "user-service": "http://user-service:5000/",\n      "app-service": "http://app-service:5000/"\n  } \n
Run Code Online (Sandbox Code Playgroud)\n\n

启动.cs:

\n\n
  services.Configure<Dictionary<string, string>>(Configuration.GetSection("services"));\n
Run Code Online (Sandbox Code Playgroud)\n\n

用法\xef\xbc\x9a

\n\n
private readonly Dictionary<string, string> _services;\npublic YourConstructor(IOptions<Dictionary<string, string>> servicesAccessor)\n{\n    _services = servicesAccessor.Value;\n}\n
Run Code Online (Sandbox Code Playgroud)\n


小智 9

您可以即时执行此操作:

appsettings.json:
{
   "MobileConfigInfo": {
      "a": "x",
      "b": "y",
      "c": "z"
    }
}
Run Code Online (Sandbox Code Playgroud)

代码中的某处:(不要忘记将 IConfiguration 依赖项添加到类构造函数中)

var yourDictionary = _configuration.GetSection("MobileConfigInfo")
                .Get<IDictionary<string, string>>();
Run Code Online (Sandbox Code Playgroud)


ste*_*-fu 7

对于简单(可能是微服务)应用程序,您可以将其添加为单例Dictionary<string, string>,然后将其注入到您需要的任何位置:

var mobileConfig = Configuration.GetSection("MobileConfigInfo")
                    .GetChildren().ToDictionary(x => x.Key, x => x.Value);

services.AddSingleton(mobileConfig);
Run Code Online (Sandbox Code Playgroud)

以及用法:

public class MyDependantClass
{
    private readonly Dictionary<string, string> _mobileConfig;

    public MyDependantClass(Dictionary<string, string> mobileConfig)
    {
        _mobileConfig = mobileConfig;
    }

    // Use your mobile config here
}
Run Code Online (Sandbox Code Playgroud)


ozz*_*zzy 6

在 .NET Core 3.1 中,您可以执行以下操作...

appsettings.json:

{
  "myConfig": {
    "foo": "bar",
    "myMappings": {
      "key1": "value1",
      "key2": "value2"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

一个配置模型

配置文件

public class MyConfig
{
    public string Foo { get; set; }
    public Dictionary<string, string> MyMappings { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

启动.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MyConfig>(configuration.GetSection("myConfig"));
Run Code Online (Sandbox Code Playgroud)

使用选项的类:

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");
    }
Run Code Online (Sandbox Code Playgroud)

这就是我使用 appsettings.json 字典映射的方式。


Jes*_*ind 5

唯一对我有用(ASP.NET Core 3.0)的是将以下内容添加到ConfigureServices方法中Startup.cs

services.Configure<Dictionary<string, string>>(dict => Configuration
    .GetSection("MySectionName")
    .GetChildren()
    .ToList()
    .ForEach(c => dict[c.Key] = c.Value));
Run Code Online (Sandbox Code Playgroud)