5

Here's what I tried:

  1. I took at a glance at the source for Host.CreateDefaultBuilder and started by setting the environment variable DOTNET_Environment to "Production". That failed.
  2. So then I tried the classic ASPNETCORE_ENVIRONMENT. Nope.
  3. Then I tried adding hostsettings.json to the root of the executing project:
{
    "Environment": "Production"
}

Nada.

How in the heck do you specify a production machine in order to use the appsettings.Production.json file?

1 Answer 1

14

Nevermind, I figured it out. I'm dumb.

First, check your Properties/launchSettings.json file for the value of "DOTNET_ENVIRONMENT". That's probably enough for most, including me.

It will, in fact, also look for a hostsettings.json file in the project root by default. It was just being overridden in my case by the launchSettings environment variable declaration.

However, if you want to use the JSON approach I mentioned in the question, but with something other than the default file name or location, you gotta call ConfigureHostConfiguration in your IHostBuilder chain and add the file explicitly.

Like so:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureHostConfiguration(
            builder =>
            {
                builder.AddJsonFile("arbitraryFileName.json");
            })
        .ConfigureServices(
            (hostContext, services) =>
            {
                services.AddHostedService<Worker>();
                services.Configure<Settings>(
                    hostContext.Configuration.GetSection("Settings"));
            });

It does indeed default to "DOTNET_" as the prefix instead of "ASPNETCORE_", so make sure both are set on your production machine/VM/service.

3
  • 1
    Have youby chance tried to use a publish profile for this service while setting the environment eg. <EnvironmentName>Dev</EnvironmentName> for the target ? Ive been trying that and it doesnt seem to work, however it works as expected for a web app.
    – bitshift
    Oct 26, 2019 at 0:56
  • Sorry I missed this! No, I have not tried it with a publish profile for a console app. However, I would still opt to set/read an environment variable on the destination machine to indicate its region (dev, stage, prod, etc). You might also be able to execute a script specific to the destination OS on publish that sets the environment. Jan 28, 2020 at 11:50
  • 1
    I'm working on a WebJob console app (dotnet 5) but nothing works for me ;-( it always says 'Production'
    – bkwdesign
    Jul 8, 2021 at 20:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.