c# - 使用 .NET Standard 2.0 从 JSON 读取配置
问题描述
我有一个 .Net Standard 2.0 类库,想从 .json 文件而不是 .config 读取配置设置。
目前我将 .config 文件读取为:
config = (CustomConfigSection)ConfigurationManager.GetSection(SectionName);
其中 CustomConfigSection 是:
public class CustomConfigSection : ConfigurationSection
{
[ConfigurationProperty("url")]
public CustomConfigElement Url
{
get => (CustomConfigElement)this["url"];
set => this["url"] = value;
}
[ConfigurationProperty("Id")]
public CustomConfigElement Id
{
get => (CustomConfigElement)this["Id"];
set => this["Id"] = value;
}
}
和
public class CustomConfigElement: ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get => (string)this["value"];
set => this["value"] = value;
}
}
我试图这样做:
var configBuilder = new ConfigurationBuilder().
SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("settings.json", optional: true, reloadOnChange: true)
.Build();
_config = (CustomConfigSection) configBuilder.GetSection(SectionName);
// Exception due to casting to inappropriate class
但我得到了例外。
所以我认为,我需要为 CustomConfigSection 类实现不是 ConfigurationSection 类而是 IConfigurationSection。
解决方案
感谢 Zysce发表评论。所以我就是这样做的,而且效果很好。
在这里,我将 CustomConfigSection 类更改为:
public class CustomConfigSection
{
public CustomConfigElement Url {get; set;}
public CustomConfigElement Id {get; set;}
}
并将 Json 配置读取为:
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
var configBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("settings.json", optional: true, reloadOnChange: true)
.Build();
_config = configBuilder.GetSection(SectionName).Get<CustomConfigSection>();
推荐阅读
- asp.net-core - 路由以允许来自查询字符串和默认 {id} 模板的参数
- javascript - 在 React 中获取输入的值并检查它
- umbraco - Umbraco:检查页面是否标记为受保护并重定向到登录
- azure - 服务总线的 Azure 函数绑定
- csv - 如何在 SOLR 中加入文档
- php - PHP 无法执行创建的命令,但 exec() 和 system() 工作正常
- php - 尝试启动 MySQL 应用程序
- r - R 绘制运行执行时间与不同输入值的关系
- haskell - 如何使用 monad 随机播放列表?
- javascript - 如何获取 HTML 标签内的值并将其绑定到 aurelia 中的 ts(组件文件)