c# - 无法从 .NET Core 2 控制台应用程序中的 config.json 读取数据

标签 c# configuration .net-core

我有以下代码。

IConfigurationRoot config = new ConfigurationBuilder()
  .SetBasePath(Directory.GetCurrentDirectory())
  .AddJsonFile("config.json", true, true)
  .Build();

string beep = config.GetSection("beep").Value;

我的 config.json 看起来像这样。

{ "beep": "bopp" }

当我遇到断点时,我可以看到有一个提供者,但其中的数据长度为零。我已经尝试了不同的方法,如 config["beep"] 等,但似乎无法获取值。它始终为 null。我正在尝试关注 the docs但一定是少了什么。

最佳答案

确保 json 文件设置为复制到目录,如 this blog 中所述.否则,当您构建或调试配置文件时,将不会包含在内。确保在属性中更改它。

您无法访问配置的原因是 IConfigurationRoot 没有引用 ConfigurationBuilder 的依赖项。为确保您的配置内容将加载,将按照以下几行做一些事情:

public static class ConfigurationProvider
{
     public static IConfiguration BuildConfiguration => new ConfigurationBuilder()
          .SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile("appsettings.json", true, true)
          .Build();
}

上面将构建我们的配置,现在我们应该使用配置。

public static class ServiceProvider
{
     public static IServiceProvider BuildServiceProvider(IServiceCollection services) => services
          .BuildDependencies()
          .BuildServiceProvider();
}

一旦我们定义了我们的提供者,我们就可以执行以下操作,以便我们可以在应用程序周围传递我们的 IConfiguration 以访问对象。

var serviceCollection = new ServiceCollection()
     .AddSingleton(configuration => ConfigurationProvider.BuildConfiguration());

var serviceProvider = ServiceProvider.BuildServiceProvider(serviceCollection);

然后在另一个类中,您将拥有以下内容:

public class SampleContext : ISampleRepository
{
     private readonly string dbConection;

     public SampleContext(IConfiguration configuration) => configuration.GetConnectionString("dbConnection");

     ...
 }

然后我们的 appsettings.json 将如下所示:

{
  "ConnectionStrings": {
    "dbConnection": "..."
  }
}

以上是json对象的正确格式。如果你有一个嵌套的对象,按照这些行:

{
     "Sample" : {
          "Api" : {
               "SampleGet" : "..."
          }
     }
}

那么你的 C# 将是:

configuration.GetSection("Sample:Api")["SampleGet"];

以上是基于你的配置和使用不在同一个顺序区域的假设,即直接在你的 main.您还应该使用 appsettings.json 因为这是默认设置,如果我没记错的话,可以减少额外的布线。您的 json 还需要正确格式化。

但这肯定会奏效,如果您需要更多帮助,请告诉我,我可以向您发送一些示例控制台核心应用程序来演示用法。

关于c# - 无法从 .NET Core 2 控制台应用程序中的 config.json 读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54262316/

相关文章:

c# - 使用 Entity Framework 6 Code First 创建 SQL View

c# - 分析 C#/.NET 应用程序

c# - EF6 和多种配置(SQL Server 和 SQL Server Compact)

.net - 如何在 .Net Core 上使用 Apache Tika?

c# - 什么更好 : id ? ? 0 == 0 或 id == null ||编号 == 0?

c# - 如何 DllExport 一个 C++ 类以在 C# 应用程序中使用

scala-加载 jar 内打包的属性文件时出错

android - 在 Android 应用程序上实现夜间模式

c# - 未发现 NUnit v3 单元测试 - "Discover test finished: 0 found"

c# - aws lambda 函数出错时如何保留 AWS SQS 消息