gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:37:27 25 4
gpt4 key购买 nike

我有以下代码。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com