JianYA
JianYA

Reputation: 3024

ASP.NET Core How to set variables for Dev, Staging and Production environments

This is my current project structure

  1. CentralRepo (Stores multiple appsettings.json files)
  2. AppOne (AppOne references CentralRepo in order to read the appsettings.json file)

Example (Program.cs):

public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(ConfigurationManager.GetBasePath(Environment.GetEnvironmentVariable("CENTRAL_REPO")))
.AddJsonFile("apponesettings.json", optional: false, reloadOnChange: true)
.Build();

public static void Main(string[] args)
{
    var logger = NLog.Web.NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
    var connectionString = Configuration["DatabaseConfiguration:ConnectionString"];
    LogManager.Configuration.Variables["connectionString"] = connectionString;
    try
    {
        logger.Debug("init main");
        BuildWebHost(args).Run();
    }
    catch (Exception ex)
    {
        //NLog: catch setup errors
        logger.Error(ex, "Stopped program because of exception");
        throw;
    }
    finally
    {
        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        NLog.LogManager.Shutdown();
    }
}

I am currently using an Environment Variable in order to set my CENTRAL_REPO path. However, I realized that when I deploy this to my development server, I can only have one environment variable with that name. How can I change this so that I can have one for development, staging and production?

Is there another way to do this rather than use environment variables?

I read about web.config files but I am unsure of how to set a variable within it and then call it from my code.

Upvotes: 0

Views: 4807

Answers (3)

Ed Gibbs
Ed Gibbs

Reputation: 26363

Environment variables can also be set in the profiles section of launchSettings.json. Look for environmentVariables and then ASPNETCORE_ENVIRONMENT.

Note there can be more than one instance. I'm never sure which profile to change so I always change them all:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:4953/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/Registrations/FindByCode?code=1234",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Staging"
      }
    },
    "My.WebService20": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/Registrations/FindByCode?code=1234",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Staging"
      },
      "applicationUrl": "http://localhost:4954/"
    }
  }
}

Upvotes: 1

nzrytmn
nzrytmn

Reputation: 6961

You can set environment variables for each environment at different json file like below ;

enter image description here

and get the variables at Startup.cs like below :

 public Startup(IHostingEnvironment env)
    {
        _env = env;
        Configuration = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables()
            .Build();
    }

Upvotes: 4

Dmitry
Dmitry

Reputation: 16825

You can set environment variable in web.config with this manual like this:

<aspNetCore processPath="dotnet"
      arguments=".\MyApp.dll"
      stdoutLogEnabled="false"
      stdoutLogFile="\\?\%home%\LogFiles\stdout"
      hostingModel="InProcess">
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
    <environmentVariable name="CONFIG_DIR" value="f:\application_config" />
  </environmentVariables>
</aspNetCore>

Upvotes: 1

Related Questions