简体   繁体   English

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

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

I am trying to learn the various ways to retrieve configuration info so I can determine the best path for setting up and using configuration for an upcoming project.我正在尝试学习检索配置信息的各种方法,以便我可以确定为即将到来的项目设置和使用配置的最佳路径。

I can access the various single settings using我可以使用访问各种单一设置

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

I also need to be able to count settings, determine values of certain settings etc. So I was building a parsing method to do these types of things and needed a whole section of the settings file, which is what I assumed GetSection did.我还需要能够计算设置,确定某些设置的值等。所以我正在构建一个解析方法来执行这些类型的事情,并且需要设置文件的整个部分,这就是我假设 GetSection 所做的。 Wrong.错误的。

appsettings file应用设置文件

{
"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."
    }
}

Below are the two screenshots of what下面是两个截图

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

returns返回

图 1:变量属性

图 2:深入到 JsonConfigurationProvider

A few questions arise.出现了几个问题。

  1. Why is this returning 3 different JsonConfigurationProviders, one of which includes every setting in the appsettings.json file (shown in Image 2)为什么这会返回 3 个不同的 JsonConfigurationProviders,其中一个包含 appsettings.json 文件中的每个设置(如图 2 所示)
  2. Why isn't GetSection("ConnectionStrings") actuall doing just that, returning the sub children of the ConnectionStrings为什么 GetSection("ConnectionStrings") 实际上不这样做,返回 ConnectionStrings 的子孩子
  3. Given number 2, how do you actually just retrieve the children of ConnectionStrings ?给定数字 2,您实际上如何检索 ConnectionStrings 的孩子?
  4. Assuming a model ConnectionStrings, with one property, List Connections, can the section be converted to an object?假设模型 ConnectionStrings 具有一个属性 List Connections,该部分是否可以转换为对象?

according to this post根据这篇文章

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

  1. the GetSection("Name").Value will return null, you must use GetChildren to get the child items GetSection("Name").Value将返回 null,您必须使用GetChildren来获取子项
  2. Bind will populate the properties aginst the provided object , by default it maps against public properties, look at the update to support private properties. Bind将填充provided object的属性,默认情况下它映射public属性,查看更新以支持private属性。
  3. try Get<T>() over bind, it will provide you a strongly typed instance of the configuration object尝试Get<T>() over bind,它将为您提供配置对象的强类型实例

try a simple POCO of your class (no complex getter/setters, all public, no methods) and then take it from there尝试一个简单的类的 POCO(没有复杂的 getter/setter,都是公共的,没有方法),然后从那里开始

Update:更新:
From .net core 2.1 BindNonPublicProperties added to BinderOptions , so if set to true (default is false) the binder will attempt to set all non read-only properties.从 .net core 2.1 BindNonPublicProperties添加到BinderOptions ,因此如果设置为 true (默认为 false),则绑定器将尝试设置所有非只读属性。

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

If you use GetSections() along with Bind() you should be able to create poco objects for your use.如果您将GetSections()Bind() GetSections()一起使用,您应该能够创建供您使用的 poco 对象。

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

This should return to you a poco object with all the values set.这应该返回给你一个设置了所有值的 poco 对象。

I understand the answer has been accepted.我知道答案已被接受。 However, providing proper example code, just in case anyone looking to understand a bit more...但是,提供正确的示例代码,以防万一有人想了解更多...

It is quite straight forward to bind custom strong type configuration.绑定自定义强类型配置非常简单。 ie.即。 configuration json looks like below配置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": ""
      }
    }
  }
}

and your C# classes looks like你的 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; }
}

You can get the section by GetSection("sectionNameWithPath") and then Convert to strong type by calling Get<T>() ;您可以通过GetSection("sectionNameWithPath")获取该部分,然后通过调用Get<T>()转换为强类型;

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

For simple string values对于简单的字符串值

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

Hope this helps...希望这有助于...

If you use the Bind method on the object returned by GetSection, then this would bind the key value pairs within the section to corresponding properties of the object it has been bound too.如果您对 GetSection 返回的对象使用 Bind 方法,那么这会将部分内的键值对绑定到它已绑定的对象的相应属性。

For example,例如,

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

.. ..

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

It works for me on .Net Core directly on Razor HTML:它直接在 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 -->

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

If you required any section with "GetSection" and (key,value), try this:如果您需要带有“GetSection”和(键,值)的任何部分,请尝试以下操作:

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

and get a Collection of keys with vallues, can manipulate with LinQ并获得带有值的键集合,可以使用 LinQ 进行操作

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

相关问题 .Net Core Configuration.GetSection()。获取&lt;&gt;()不绑定 - .Net Core Configuration.GetSection().Get<>() not binding ASP.net Core 2.0中的appsettings.json预览配置GetSection null - appsettings.json in ASP.net Core 2.0 Preview configuration GetSection null ASP.NET Core:JSON 配置 GetSection 返回 null - ASP.NET Core: JSON Configuration GetSection returns null 使用手动添加的 settings.json 文件到 dotnet 核心控制台应用程序时,Configuration.GetSection(“SectionName”) 始终为 null - Configuration.GetSection(“SectionName”) is always null when using manually added settings.json file to dotnet core console app ASP.NET Core中的抽象设置配置 - Abstract Settings Configuration in ASP.NET Core .NET自定义配置部分:Configuration.GetSection引发“无法找到程序集”异常 - .NET custom configuration section: Configuration.GetSection throws 'unable to locate assembly' exception Configuration.GetSection(“的connectionStringName”)。获取 <?> 总是为空 - Configuration.GetSection(“ConnectionStringName”).Get<?> always null Configuration.GetSection返回null值 - Configuration.GetSection returns null value 如何使用 FakeItEasy 语法模拟 configuration.GetSection? - How to mock configuration.GetSection with FakeItEasy syntax? 为什么 static Configuration.GetSection() 不可用? - Why is static Configuration.GetSection() not available?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM