简体   繁体   中英

Appsettings.Development.json do not seen by console app .net core 3.1 configuration problem

In my asp.net core 3.1 console app. In main class I have code like this:

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();
    }
}

Environment set to Development在此处输入图像描述

and config files like this (only values there differ):

在此处输入图像描述

My app keeps taking values from appsettings.json. What to change in order to take values from appsettings.Developement.json?

I also tried like this, but it didn`t work either:

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

            .AddEnvironmentVariables();
    }

Does anyone can help with that? Files are properly copied to bin 在此处输入图像描述

I just wanted to confirm that the DOTNET_ENVIRONMENT variable worked for me as well, but wanted to add that in Visual Studio 2022 in my.Net 6 Console App I had to configure the value in Launch Profiles, which I navigated to via the Debug Section in Project Properties: 在此处输入图像描述

I also did NOT need to add the appsettings.Develepment.json file to the builder when I tested this.

All I have in my Program.cs for configuring dependency injection, is this:

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");

I found this on GitHub: https://github.com/aspnet/Hosting/issues/1440 .

I think the problem is that the ConfigurationBuilder isn't reading the launchsettings. I added the following to fix that.

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();
            }
        }

I had the same problem with my console application with default configuration providers. And the reason was the incorrect Environment variable like in your screenshot - ASPNETCORE_ENVIRONMENT. And I fixed it by replacing it by DOTNET_ENVIRONMENT:

在此处输入图像描述

For.Net 6.0

Add the environment variable DOTNET_ENVIRONMENT=Development

Restart Visual Studio 2022.

环境变量

what worked for me was setting the Copy to Output Directory to Copy if newer

.NET 3.1 - WPF app

在此处输入图像描述

In .NET 5 and higher the setting is called DOTNET_ENVIRONMENT

In your launchprofile.json you should see something like this

  "environmentVariables": {
    "DOTNET_ENVIRONMENT": "Development"
  }

You don't need this piece of code anymore

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

The hostbuilder will do this for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM