繁体   English   中英

Asp.Net Core 2.0 中的 Configuration.GetSection 获取所有设置

[英]Configuration.GetSection in Asp.Net Core 2.0 getting all settings

我正在尝试学习检索配置信息的各种方法,以便我可以确定为即将到来的项目设置和使用配置的最佳路径。

我可以使用访问各种单一设置

var sm = new SmsSettings
    {
        FromPhone = Configuration.GetValue<string>("SmsSettings:FromPhone"),               
        StartMessagePart = Configuration.GetValue<string>("SmsSettings:StartMessagePart"),               
        EndMessagePart = Configuration.GetValue<string>("SmsSettings:EndMessagePart")
    };

我还需要能够计算设置,确定某些设置的值等。所以我正在构建一个解析方法来执行这些类型的事情,并且需要设置文件的整个部分,这就是我假设 GetSection 所做的。 错误的。

应用设置文件

{
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo;Trusted_Connection=True;MultipleActiveResultSets=true",
  "ProductionConnection": "Server=(localdb)\\mssqllocaldb;Database=TestingConfigurationNetCoreTwo_Production;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
  "IncludeScopes": false,
  "LogLevel": {
    "Default": "Warning"
  }
},   
"SmsSettings": {
  "FromPhone": "9145670987",      
  "StartMessagePart": "Dear user, You have requested info from us on starting",      
  "EndMessagePart": "Thank you."
    }
}

下面是两个截图

var section = Configuration.GetSection("ConnectionStrings");

返回

图 1:变量属性

图 2:深入到 JsonConfigurationProvider

出现了几个问题。

  1. 为什么这会返回 3 个不同的 JsonConfigurationProviders,其中一个包含 appsettings.json 文件中的每个设置(如图 2 所示)
  2. 为什么 GetSection("ConnectionStrings") 实际上不这样做,返回 ConnectionStrings 的子孩子
  3. 给定数字 2,您实际上如何检索 ConnectionStrings 的孩子?
  4. 假设模型 ConnectionStrings 具有一个属性 List Connections,该部分是否可以转换为对象?

根据这篇文章

https://github.com/aspnet/Configuration/issues/716

  1. GetSection("Name").Value将返回 null,您必须使用GetChildren来获取子项
  2. Bind将填充provided object的属性,默认情况下它映射public属性,查看更新以支持private属性。
  3. 尝试Get<T>() over bind,它将为您提供配置对象的强类型实例

尝试一个简单的类的 POCO(没有复杂的 getter/setter,都是公共的,没有方法),然后从那里开始

更新:
从 .net core 2.1 BindNonPublicProperties添加到BinderOptions ,因此如果设置为 true (默认为 false),则绑定器将尝试设置所有非只读属性。

var yourPoco = new PocoClass();
Configuration.GetSection("SectionName").Bind(yourPoco, c => c.BindNonPublicProperties = true)

如果您将GetSections()Bind() GetSections()一起使用,您应该能够创建供您使用的 poco 对象。

var poco= new PocoClass();
Configuration.GetSection("SmsSettings").Bind(poco);

这应该返回给你一个设置了所有值的 poco 对象。

我知道答案已被接受。 但是,提供正确的示例代码,以防万一有人想了解更多...

绑定自定义强类型配置非常简单。 即。 配置json如下所示

{
  "AppSettings": {
    "v": true,
    "SmsSettings": {
      "FromPhone": "9145670987",
      "StartMessagePart": "Dear user, You have requested info from us on starting",
      "EndMessagePart": "Thank you."
    },
    "Auth2Keys": {
      "Google": {
        "ClientId": "",
        "ClientSecret": ""
      },
      "Microsoft": {
        "ClientId": "",
        "ClientSecret": ""
      },
      "JWT": {
        "SecretKey": "",
        "Issuer": ""
      }
    }
  }
}

你的 C# 类看起来像

public class SmsSettings{
    public string FromPhone { get; set;}
    public string StartMessagePart { get; set;}
    public string EndMessagePart { get; set;}
}

public class ClientSecretKeys
{
    public string ClientId { get; set; }
    public string ClientSecret { get; set; }
}

public class JWTKeys
{
    public string SecretKey { get; set; }
    public string Issuer { get; set; }
}

public class Auth2Keys
{
    public ClientSecretKeys Google { get; set; }
    public ClientSecretKeys Microsoft { get; set; }
    public JWTKeys JWT { get; set; }
}

您可以通过GetSection("sectionNameWithPath")获取该部分,然后通过调用Get<T>()转换为强类型;

var smsSettings = Configuration.GetSection("AppSettings:SmsSettings").Get<SmsSettings>();
var auth2Keys= Configuration.GetSection("AppSettings:Auth2Keys").Get<Auth2Keys>();

对于简单的字符串值

var isDebugMode = Configuration.GetValue("AppSettings:IsDebugMode");

希望这有助于...

如果您对 GetSection 返回的对象使用 Bind 方法,那么这会将部分内的键值对绑定到它已绑定的对象的相应属性。

例如,

class ConnectionStrings {
  public string DefaultConnection { get; set;}
  public string ProductionConnection {get; set;}
}

..

var connectionStrings = new ConnectionStrings();
var section = Configuration.GetSection("ConnectionStrings").Bind(connectionStrings);

它直接在 Razor HTML 上适用于 .Net Core:

@Html.Raw(Configuration.GetSection("ConnectionStrings")["DefaultConnectoin"]) <!-- 2 levels -->
@Html.Raw(Configuration.GetSection("Logging")["LogLevel:Default"]) <!-- 3 levels -->
@Html.Raw(Configuration.GetSection("SmsSettings")["EndMessagePart"]) <!-- 2 levels -->

参考: https : //www.red-gate.com/simple-talk/dotnet/net-development/asp-net-core-3-0-configuration-factsheet/

如果您需要带有“GetSection”和(键,值)的任何部分,请尝试以下操作:

Configuration.GetSection("sectionName").GetChildren().ToList()

并获得带有值的键集合,可以使用 LinQ 进行操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM