Publish a .NET Core Console application with right transformation settings

adv*_*api 1 c# .net-core

I'm quite new to .NET Core application, and I was wondering if there's a simple way to deploy the right application.json based on the profile. In .NET Standard application it was quite simple since we have web.config transformation/Slowcheeta but It doesn't seems to work with .NET Core Console app.

I've also read online that with ASP.NET Core application, we can use

var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) <--this
.AddEnvironmentVariables();
Configuration = builder.Build();
Run Code Online (Sandbox Code Playgroud)

But on .NET Console app I don't have an env.EnvironmentName

I've also read that someone uses a #IF-#ENDIF statement to switch but this requires to put hands on code if a new publish profile is created

Any suggestion_

Thu*_*kwa 5

为了改进我通过@MarkusDresch 投票的答案,我想知道 OP 是否说这仍然不起作用,因为他们没有设置正确的环境。您需要正确设置它,例如从 hostsetting.json 的 env 变量:

            var host = new HostBuilder()
                   .ConfigureHostConfiguration(builder =>
                   {
                       builder.AddJsonFile("hostsettings.json", optional: true);
                   })
                   .ConfigureAppConfiguration((hostContext, builder) =>
                   {
                       builder.AddJsonFile("appsettings.json");
                       builder.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true);
                   })
Run Code Online (Sandbox Code Playgroud)

在此示例中,hostsettings.json 将具有以下内容:

{
  "environment": "Development",
}
Run Code Online (Sandbox Code Playgroud)