Appsettings.Development.json文件未被.NET Core 3.1控制台应用程序识别,配置问题

7
在我的 asp.net core 3.1 控制台应用程序中,主类中有如下代码:
class Program
{
    static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder();
        BuildConfig(builder);

        var host = Host.CreateDefaultBuilder()
            .ConfigureServices((context, services) =>
            {
                services.AddTransient<StartService>();
            })
            .Build();
        
        var svc = ActivatorUtilities.CreateInstance<StartService>(host.Services);
        
        svc.Run();
    }

    static void BuildConfig(IConfigurationBuilder builder)
    {
        builder.SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
           .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json", optional: true)

            .AddEnvironmentVariables();
    }
}

环境设置为开发环境 enter image description here

配置文件如下(只有值不同):

enter image description here

我的应用程序继续从appsettings.json中获取值。如何更改以从appsettings.Developement.json中获取值?

我也尝试了这样做,但也没有起作用:

    static void BuildConfig(IConfigurationBuilder builder)
    {
        builder.SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
           .AddJsonFile("appsettings.Development.json", optional: true)

            .AddEnvironmentVariables();
    }

有人能帮忙吗? 文件已正确复制到bin目录下。 在这里输入图片描述


1
尝试 .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true) - Nonik
有人可以帮忙吗? - Piotr P
@YiyiYou,那也不行,即使我没有指定路径,设置仍然从appsettings.json中获取。 - Piotr P
你有没有找到解决办法?我也遇到了完全相同的问题。 - yush
您不再需要 addjsonfile 部分。hostbuilder 将为您完成此操作。 - Enrico
显示剩余2条评论
6个回答

7

我的控制台应用程序也遇到了与默认配置提供程序相关的相同问题。原因是像您截图中的ASPNETCORE_ENVIRONMENT这样不正确的环境变量。

我通过将其替换为DOTNET_ENVIRONMENT来解决了这个问题:

enter image description here


1
我不得不说我很震惊!这是绝对正确的!!我接手了一个从未正常工作过的控制台应用程序项目,现在我知道其中一个原因是因为它定义了ASPNETCORE_ENVIRONMENT而不是DOTNET_ENVIRONMENT。非常感谢您分享这个信息。 - Vida
太棒了!谢谢分享。 - Ayoub Khayati

5

针对 .Net 6.0:

添加环境变量 DOTNET_ENVIRONMENT=Development

重新启动 Visual Studio 2022。

环境变量


2
你不需要在系统属性中设置这个。你可以在Visual Studio中使用启动配置文件来完成。 - Enrico

4
我只想确认 DOTNET_ENVIRONMENT 变量对我也起作用了,但是我想补充一下,在我的 .Net 6 控制台应用程序的 Visual Studio 2022 中,我不得不通过“项目属性”中的“调试”部分导航到“启动配置文件”中配置该值: enter image description here 当我测试时,我也不需要将 appsettings.Development.json 文件添加到构建器中。
我在 Program.cs 中只有以下内容来配置依赖注入:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Console.WriteLine("Starting...");

using var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((_, services) =>
    {
        services.AddTransient<ISqlServerTests, SqlServerTests>();
    })
    .Build();

Console.WriteLine("Done");

提醒一下,如果尝试从ASP .NET Core应用程序运行控制台应用程序,则可能会出现一些奇怪的情况。使用此方法时,似乎会使用调用应用程序的appsettings。 - George Fabish

1
在 .NET 5 及更高版本中,该设置被称为 DOTNET_ENVIRONMENT
在您的 launchprofile.json 文件中,您应该看到类似以下内容的代码:
  "environmentVariables": {
    "DOTNET_ENVIRONMENT": "Development"
  }

你不再需要这段代码了

 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
 .AddJsonFile("appsettings.Development.json", optional: true)

hostbuilder会为您完成这个任务。


0

对我有效的方法是将复制到输出目录设置为仅在较新时复制

.NET 3.1 - WPF 应用程序

enter image description here


0
我在 GitHub 上找到了这个:https://github.com/aspnet/Hosting/issues/1440
我认为问题在于 ConfigurationBuilder 没有读取 launchsettings。我添加了以下内容来解决这个问题。
static async Task Main(string[] args)
        {
            var builder = new HostBuilder();
            builder
                .ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices();
                    //b.AddAzureStorage();
                    b.AddTimers();
                })
                .ConfigureHostConfiguration(configHost =>
                {
                    configHost.AddEnvironmentVariables(prefix: "ASPNETCORE_");
                    configHost.AddCommandLine(args);
                })
                .ConfigureAppConfiguration((hostingContext, config) => 
                {
                    var env = hostingContext.HostingEnvironment;

                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                })
                .ConfigureLogging((context, b) =>
                {
                    b.AddConsole();
                });
            var host = builder.Build();
            using (host)
            {
                // The following code ensures that the WebJob will be running continuously
                await host.RunAsync();
            }
        }

这段代码应该放在哪里?你能具体一点吗? - Dbloom
现在我再看原始帖子,ConfigurationBuilder已经配置但尚未使用。然后Host在没有配置的情况下被实例化。我认为我的问题与OP不同。 - Sean Howard
@SeanHoward 感谢您提供的信息,但正如我所说,我甚至尝试将其硬编码为 .AddJsonFile("appsettings.Development.json", optional: true),但它仍然无法工作。因此,我不认为这些是导致问题的环境变量。 - Piotr P
就像我说的那样,您在生成器上调用了.AddJsonFile,但是您将主机传递给了ActivatorUtilities.CreateInstance<StartService>。生成器也许没有什么作用。 - Sean Howard

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