小编典典

在.Net Core中使用app.config

c#

我有问题。我需要在.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下载-安装包CoreCompat.System.Configuration-版本4.2.3-r4
-Pre,仍然无法正常工作。也许有人可以帮我吗?


阅读 1804

收藏
2020-05-19

共1个答案

小编典典

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

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

注意:当有人说配置文件应该是时,请不要感到困惑appsettings.json。您可以使用任何适合您的文件名,文件位置可能有所不同-没有特定的规则。

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

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

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

  1. 实际上,app.config配置文件是一个XML文件。因此,您可以使用XML配置提供程序(位于github上的源代码nuget链接)从中读取设置。但请记住,它将仅用作配置源-您的应用行为的任何逻辑都应由您实现。配置提供程序不会更改应用程序的“设置”和设置策略,而只会从文件中读取数据。
2020-05-19