Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何检查配置节是否存在?_C#_Asp.net Core_.net Core_App Config - Fatal编程技术网

C# 如何检查配置节是否存在?

C# 如何检查配置节是否存在?,c#,asp.net-core,.net-core,app-config,C#,Asp.net Core,.net Core,App Config,我正在尝试为我的dotnet核心项目实现一个简单的配置服务 如果添加的任何配置文件中不存在请求的配置节,我想返回null 检索配置节的当前代码: private static IConfigurationRoot _configuration { get; set; } private static IConfigurationBuilder _builder; public JsonConfigService() { _builder = new ConfigurationBuilde

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

如果添加的任何配置文件中不存在请求的配置节,我想
返回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();
}
私有静态IConfigurationRoot\u配置{get;set;}
私有静态IConfigurationBuilder\u builder;
公共JsonConfigService()
{
_builder=新配置builder();
}
public T GetConfigModel(字符串名称),其中T:new()
{
if(string.IsNullOrWhiteSpace(name))
返回默认值(T);
var section=\u configuration.GetSection(名称);
if(section==null | | string.IsNullOrWhiteSpace(section.Value))
返回默认值(T);
var值=新的T();
第节绑定(值);
返回值;
} 
公共无效注册表源(字符串源)
{
_builder.AddJsonFile(源代码);
_配置=_builder.Build();
}
问题是:

  • 只要请求的配置节在配置中可用或不可用,则该节永远不会为null
  • section.Value
    始终为空(仅针对复杂类型进行测试)

在绑定之前,如何确定配置节“NotHere”是否实际在json文件中?

使用
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;
    }
}
public T GetConfigModel(字符串名称),其中T:new()
{
if(string.IsNullOrWhiteSpace(name))
返回默认值(T);
尝试
{
返回_configuration.GetValue(名称);
}
捕获(例外情况除外)
{
掷骰子;
}
}

您可以
配置节绑定到一个模型类,如果该节不存在,这将导致
null