【问题标题】:Map appsettings.json to class将 appsettings.json 映射到类
【发布时间】:2021-01-18 22:02:01
【问题描述】:

我正在尝试将 appsettings.json 转换为 C# 类

我使用Microsoft.Extensions.Configuration从appsettings.json读取配置

我使用反射编写了以下代码,但我正在寻找更好的解决方案

foreach (var (key, value) in configuration.AsEnumerable())
{
    var property = Settings.GetType().GetProperty(key);
    if (property == null) continue;
    
    object obj = value;
    if (property.PropertyType.FullName == typeof(int).FullName)
        obj = int.Parse(value);
    if (property.PropertyType.FullName == typeof(long).FullName)
        obj = long.Parse(value);
    property.SetValue(Settings, obj);
}

【问题讨论】:

    标签: c# .net-core configuration


    【解决方案1】:

    appsettings.json 文件构建配置:

    var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional = false)
                .Build()
    

    然后添加 Microsoft.Extensions.Configuration.Binder nuget 包。您将拥有将配置(或配置部分)绑定到现有或新对象的扩展。

    例如你有一个设置类(顺便说一句,它被称为选项)

    public class Settings
    {
        public string Foo { get; set; }
        public int Bar { get; set; }
    }
    

    还有appsettings.json

    {
      "Foo": "Bob",
      "Bar": 42
    }
    

    要将配置绑定到新对象,您可以使用Get<T>() 扩展方法:

    var settings = config.Get<Settings>();
    

    要绑定到现有对象,您可以使用Bind(obj):

    var settings = new Settings();
    config.Bind(settings);
    

    【讨论】:

    • 没有Get和Bind方法
    • @AliRezaBeigy 然后错过了添加 Microsoft.Extensions.Configuration.Binder 包的部分
    • @AliRezaBeigy 有点晚了,我有这个,我没有在实例化配置变量的末尾添加 .Build()
    【解决方案2】:

    您可以使用Dictionary获取json,然后使用JsonSerializer转换json。

    public IActionResult get()
        {
            Dictionary<string, object> settings = configuration
            .GetSection("Settings")
            .Get<Dictionary<string, object>>();
            string json = System.Text.Json.JsonSerializer.Serialize(settings);
    
            var setting = System.Text.Json.JsonSerializer.Deserialize<Settings>(json);
    
            return Ok();
        }
    

    这是模型

    public class Settings
    {
        public string property1 { get; set; }
        public string property2 { get; set; }
    }
    

    在 appsettings.json 中

     "Settings": {
      "property1": "ap1",
      "property2": "ap2"
     },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-16
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 2012-02-13
      • 2022-11-19
      • 1970-01-01
      • 2016-10-02
      相关资源
      最近更新 更多