我有问题.我需要在.Net Core(C#)中编写一个使用app.config的程序,如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="custom" type="ConfigurationSample.CustomConfigurationSection, ConfigurationSample"/>
</configSections>
<connectionStrings>
<add name="sampleDatabase" connectionString="Data Source=localhost\SQLExpress;Initial Catalog=SampleDatabase;Integrated Security=True"/>
</connectionStrings>
<appSettings>
<add key="sampleApplication" value="Configuration Sample"/>
</appSettings>
<custom>
<customConfigurations>
<add key="customSample" name="Mickey Mouse" age="83"/>
</customConfigurations>
</custom>
</configuration>
Run Code Online (Sandbox Code Playgroud)
我写道:
string connectionString = ConfigurationManager.ConnectionStrings["sampleDatabase"].ConnectionString;
Console.WriteLine(connectionString);
// read appSettings configuration
string appSettingValue = ConfigurationManager.AppSettings["sampleApplication"];
Console.WriteLine(appSettingValue);
Run Code Online (Sandbox Code Playgroud)
它是来自互联网的例子,所以我认为会工作,但我得到例外:
System.Configuration.ConfigurationErrorsException: 'Error Initializing the configuration system.'
Inner Exception
TypeLoadException: Could not load type 'System.Configuration.InternalConfigurationHost' from assembly 'CoreCompat.System.Configuration, Version=4.2.3.0, Culture=neutral, PublicKeyToken=null' because the method 'get_bundled_machine_config' has no implementation (no RVA).
Run Code Online (Sandbox Code Playgroud)
我通过NuGet下载 - 安装 - 包CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre仍然无法正常工作.也许有人可以帮助我?
Dee*_*101 34
System.Configuration
甚至可以在Linux上使用.NET Core 2.0.试试这个测试示例:
MyLib.dll
)System.Configuration.ConfigurationManager
v4.4.0.这是必需的,因为这个包不包含在meta-package NetStandard.Library
v2.0.0中(我希望更改)ConfigurationSection
或ConfigurationElement
进入MyLib.dll
.例如,MyClass.cs
派生自ConfigurationSection
和MyAccount.cs
派生自ConfigurationElement
.实施细节不在此范围,但谷歌是您的朋友MyApp.dll
)..NET核心应用程序以.dll
而不是.exe
框架结束.app.config
in MyApp
.这显然应该与上面#3中的班级设计相匹配.例如:<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
</configSections>
<myCustomConfig>
<myAccount id="007" />
</myCustomConfig>
</configuration>
Run Code Online (Sandbox Code Playgroud)
就是这样 - 你会发现app.config被正确解析MyApp
并且你现有的代码MyLib
工作得很好.dotnet restore
如果您将平台从Windows(dev)切换到Linux(测试),请不要忘记运行.
Set*_*Set 25
您可以将Configuration API与任何 .NET Core应用程序一起使用,而不仅仅是ASP.NET Core应用程序.查看链接中提供的示例,其中显示了如何在控制台应用程序中读取配置.
在大多数情况下,JSON源(读作.json
文件)是最合适的配置源.
注意:当有人说配置文件应该是时,不要混淆
appsettings.json
.您可以使用任何适合您的文件名,文件位置可能不同 - 没有具体规则.
但是,由于现实世界很复杂,有很多不同的配置提供商:
等等.您甚至可以使用/编写自定义提供程序.
实际上,app.config
配置文件是一个XML文件.因此,您可以使用XML配置提供程序(github上的源代码,nuget链接)从中读取设置.但请记住,它仅用作配置源 - 您的应用程序行为应该由您实现.配置提供程序不会更改"设置"并为您的应用设置策略,而只会从文件中读取数据.
jlo*_*ail 12
我有一个具有类似问题的 .Net Core 3.1 MSTest 项目。这篇文章提供了修复它的线索。
将其分解为 .Net core 3.1 的简单答案:
如果是 MSTest 项目:
将项目中的文件重命名为 testhost.dll.config
或者
使用 DeepSpace101 提供的 post-build 命令
归档时间: |
|
查看次数: |
73024 次 |
最近记录: |