【问题标题】:How to check if config section exists?如何检查配置部分是否存在?
【发布时间】:2017-08-23 21:18:33
【问题描述】:

我正在尝试为我的 dotnet 核心项目实施一个简单的配置服务。

如果添加的任何配置文件中都不存在请求的配置部分,我想return null

我当前检索配置部分的代码:

private static IConfigurationRoot _configuration { get; set; }
private static IConfigurationBuilder _builder;

public JsonConfigService()
{
   _builder = new ConfigurationBuilder();

}

public T GetConfigModel<T>(string name) where T : new()
{
    if (string.IsNullOrWhiteSpace(name))
        return default(T);

    var section = _configuration.GetSection(name);

    if (section == null || string.IsNullOrWhiteSpace(section.Value))
        return default(T);

    var value = new T();
    section.Bind(value);

    return value;
} 

public void RegisterSource(string source)
{
    _builder.AddJsonFile(source);
    _configuration = _builder.Build();
}

问题是:

  • 只要请求的配置部分在配置中是否可用,部分就永远不会为空。
  • section.Value 始终为 null(仅针对复杂类型进行测试)

我如何在绑定之前确定配置部分“NotHere”是否实际上在 json 文件中?

【问题讨论】:

  • 您可以将配置节Bind 设置为模型类,如果节不存在,这将导致null

标签: c# asp.net-core .net-core app-config


【解决方案1】:

如果配置中不存在该部分,则使用 GetValue 方法而不是 GetSection 返回 null

用法:

public T GetConfigModel<T>(string name) where T : new()
{
    if (string.IsNullOrWhiteSpace(name))
        return default(T);

    try
    {
        return _configuration.GetValue<T>(name);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 2021-12-02
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多