在.Net Core中使用app.config

95

我有问题。我需要在 .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>

而我写道:

string connectionString = ConfigurationManager.ConnectionStrings["sampleDatabase"].ConnectionString;
Console.WriteLine(connectionString);

// read appSettings configuration
string appSettingValue = ConfigurationManager.AppSettings["sampleApplication"];
Console.WriteLine(appSettingValue);

这个例子是从互联网上找到的,我以为能够正常运行,但是我遇到了异常:

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).

我通过NuGet下载了 - Install-Package CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre,但仍然无法运行。也许有人可以帮助我吗?


3
我认为对于 .NET Core,你会使用 JSON 文件进行配置。查阅相关资料。 - Phiter
3
在.NET Core中,你需要使用 appsettings.json 而不是 app.config。 - Camilo Terevinto
1
但是我说的是 .Net Core 而不是 ASP.Net Core。 - Nju
16
这是网络上的例子,所以我认为会有效 - 这是有史以来最大的误解。 - Sahil Sharma
5
微软还发布了一个NuGet包,允许您在.NET Core中使用经典的配置文件。 https://www.nuget.org/packages/System.Configuration.ConfigurationManager - William
这可能与未来的访问者有关。https://dev59.com/VVYN5IYBdhLWcg3wuaNx#50572248 - Victor Zakharov
4个回答

96

即使在 Linux 上使用 .NET Core 2.0,您仍可以使用常规的 System.Configuration。尝试使用以下测试示例:

  1. 创建一个 .NET Standard 2.0 库(例如 MyLib.dll)。
  2. 添加 NuGet 包 System.Configuration.ConfigurationManager v4.4.0。这是必需的,因为此包未被元包 NetStandard.Library v2.0.0 所包含(我希望会发生改变)。
  3. 所有从 ConfigurationSectionConfigurationElement 派生的 C# 类都放在 MyLib.dll 中。例如,MyClass.cs 派生自 ConfigurationSection,而 MyAccount.cs 派生自 ConfigurationElement。实现细节不在此范围之内,但Google 是您的好帮手。
  4. 创建一个 .NET Core 2.0 应用程序(例如控制台应用程序,MyApp.dll)。.NET Core 应用程序以 .dll 结尾,而不是 Framework 中的 .exe
  5. MyApp 中创建一个 app.config,其中包含您的自定义配置部分。这显然应该与上面步骤 3 中的类设计相匹配。例如:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
  </configSections>
  <myCustomConfig>
    <myAccount id="007" />
  </myCustomConfig>
</configuration>

就是这样 - 你会发现在MyApp中正确解析了app.config,并且你现有的MyLib代码仍然可以正常工作。如果从Windows(dev)切换到Linux(test),不要忘记运行dotnet restore

此外,运行时的app.config位置与.NET Framework中的不同,而是在.NET Core中为"projectName.dll.config",而不是"projectName.exe.config"。

测试项目的额外解决方法

如果您发现您的App.config在测试项目中无法正常工作,则可能需要将此片段放入您的测试项目的.csproj中(例如,在结束的</Project>之前)。它基本上将App.config复制到您的输出文件夹中,命名为testhost.dll.config,以便dotnet test可以使用它。

  <!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
  <Target Name="CopyCustomContent" AfterTargets="AfterBuild">
    <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
  </Target>
  <!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->

1
如果能避免这个微不足道的问题,那么从.NET Framework迁移到.NET Core将会非常快速和容易,这应该是正确答案。 - cuongle
感谢您提供的测试项目解决方案!如果测试项目与主项目是分开的,建议将App.config从主项目复制过来,以避免在测试项目中出现重复的副本。只需从上面的路径..\MainProject\App.config复制,而不是从App.config复制。 - MikeBeaton
这只是一个临时修复方法,让我很困扰的是有这么多人认为这样的临时修复方法是可以接受的。我并不打算维护自定义配置管理器。 - JSON

49
  1. 您可以在任何.NET Core应用程序中使用Microsoft.Extensions.Configuration API,而不仅仅是在ASP.NET Core应用程序中。 请查看链接提供的示例,该示例展示了如何在控制台应用程序中读取配置。

  2. 在大多数情况下,JSON源(表示为.json文件)是最适合的配置源。

    注意:当有人说配置文件应该是appsettings.json时,请勿混淆。您可以使用任何适合您的文件名,并且文件位置可能不同-没有具体规则。

    但是,由于现实世界很复杂,有很多不同的配置提供程序:

    • 文件格式(INI、JSON和XML)
    • 命令行参数
    • 环境变量

    等等。您甚至可以使用/编写自定义提供程序。

  3. 实际上,app.config配置文件是一个XML文件。因此,您可以使用XML配置提供程序从中读取设置(github源代码nuget链接)。但是请注意,它将仅用作配置源-您应该自己实现应用程序的任何行为逻辑。配置提供程序不会更改“设置”并为应用程序设置策略,而只会从文件中读取数据。


20
我有一个 .Net Core 3.1 MSTest 项目,类似的问题。这篇文章提供了解决方法的线索。
简单回答 .Net core 3.1 的解决方法:
- 添加/确保项目中有NuGet包: System.Configuration.ConfigurationManager - 将你的 app.config(xml) 添加到项目中。
如果是MSTest项目:
- 将项目中的文件重命名为 testhost.dll.config
或者
- 使用 DeepSpace101 提供的后置构建命令

这对我有用,但我不得不手动将testhost.dll.config复制到bin文件夹中。 - Max

2

我不想再引入其他依赖项,所以选择了以下方案:

class Main
{
    private static readonly NameValueCollection AppSettings = ConfigurationManager.AppSettings;

    public static void Main(string[] args)
    {
        var appSettings = new MemoryConfigurationSource
        {
            InitialData = AppSettings.AllKeys.ToDictionary(key => key, key => AppSettings[key]),
        };
        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Add(appSettings)
            .Build();
    }
}

只需将ConfigurationManager.AppSettings映射到MemoryConfigurationSource即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接