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

时间:2017-11-22 11:01:35

标签: configuration asp.net-core-2.0

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

我可以使用

访问各种单一设置
var sm = new SmsSettings
    {
        FromPhone = Configuration.GetValue<string>("SmsSettings:FromPhone"),               
        StartMessagePart = Configuration.GetValue<string>("SmsSettings:StartMessagePart"),               
        EndMessagePart = Configuration.GetValue<string>("SmsSettings:EndMessagePart")
    };

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

appsettings文件

{
"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");

返回

Image 1: variable properties

Image 2: Drilling down into JsonConfigurationProvider

出现了一些问题。

  1. 为什么这会返回3个不同的JsonConfigurationProviders,其中一个包含appsettings.json文件中的每个设置(如图2所示)
  2. 为什么没有GetSection(&#34; ConnectionStrings&#34;)实现这一点,返回ConnectionStrings的子子
  3. 鉴于数字2,您如何才能真正检索ConnectionStrings的子项?
  4. 假设模型ConnectionStrings具有一个属性List Connections,该部分可以转换为对象吗?

6 个答案:

答案 0 :(得分:10)

我知道答案已被接受。但是,提供适当的示例代码,以防万一希望了解更多内容的人...

绑定自定义强类型配置非常简单。即。配置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”);

希望这对您有帮助...

答案 1 :(得分:6)

根据这篇文章

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

  1. GetSection("Name").Value将返回null,您必须使用GetChildren来获取子项目
  2. Bind可能无法对您的对象起作用,请确保属性为public
  3. 尝试Get<T>() over bind,它将为您提供配置对象的强类型实例
  4. 尝试一下你班级的简单POCO(没有复杂的getter / setter,所有公共,没有方法),然后从那里拿出来

答案 2 :(得分:2)

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

例如,

    ID    Name         Salary($)
     0    AXXX XXXX     44,000
     1    BXX XXXXX     65,000
     2    PXXXX XXXXX   50,000

...

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

答案 3 :(得分:2)

如果将GetSections()Bind()一起使用,则应该可以创建poco对象供您使用。

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

这应该为您返回一个已设置所有值的poco对象。

答案 4 :(得分:1)

它直接在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/

答案 5 :(得分:0)

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

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

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