完整.NET Framework控制台应用程序中的JSON配置 [英] JSON Configuration in full .NET Framework Console App
问题描述
我有一个针对.NET 4.7.1的控制台应用程序.我正在尝试在.Net Framework应用程序中使用.net核心之类的配置.我的App.config是:
I have a Console App targeting .NET 4.7.1. I'm trying to use .net core like configuration in my .Net Framework app. My `App.config is:
<configuration>
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" />
</configSections>
<configBuilders>
<builders>
<add name="SimpleJson"
jsonFile="config.json"
optional="false"
jsonMode="Sectional"
type="Microsoft.Configuration.ConfigurationBuilders.SimpleJsonConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Json, Version=1.0.0.0, Culture=neutral" /></builders>
</configBuilders>
我有一个文件config.json
,其属性始终复制"设置为True
. config.json
看起来像:
And I have a file config.json
which has property "Copy Always" set to True
. config.json
looks like:
{
"appSettings": {
"setting1": "value1",
"setting2": "value2",
"complex": {
"setting1": "complex:value1",
"setting2": "complex:value2"
}
},
"connectionStrings": {
"mySpecialConnectionString": "Dont_check_connection_information_into_source_control"
}
}
然后,在我的main
方法中,我尝试读取一个配置值,例如:
Then, in my main
method, I try to read a config value like:
var config = ConfigurationManager.AppSettings
但是,config
的值始终为null.我尝试了以下方法:
However, the value of config
is always null. I tried the following:
- 试图将
jsonFile
更改为~/config.json
; - 尝试在将
jsonMode
设置为flat的默认值时提供非常基本的键值(flat)json配置;
- Tried changing
jsonFile
to~/config.json
; - Tried giving a very basic key-value (flat) json config while setting
jsonMode
to default value of flat;
但是,无法使配置正常工作.我该如何解决这个问题?
But, can't get the config to work. How can I fix this issue?
推荐答案
如果要像.Net Core中一样使用config json文件,则可以安装NuGets Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.Json 然后初始化配置
If you want to use config json files as in .Net Core, you can install NuGets Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.Json and then initialize the configuration
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("config.json", optional: true)
.Build();
此后,您可以使用.Net Core中的配置.例如:
After this you can use configuration as in .Net Core. For example:
{
"myConfig": {
"item1": "config options"
}
}
对于此json,您将调用:
For this json you will call:
var configItem = configuration["myConfig:item1"];
这篇关于完整.NET Framework控制台应用程序中的JSON配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!