Skip to content

Instantly share code, notes, and snippets.

@hoetz
Last active July 26, 2018 13:59
Show Gist options
  • Save hoetz/56beaf9f73fdd845cd1d751451520094 to your computer and use it in GitHub Desktop.
Save hoetz/56beaf9f73fdd845cd1d751451520094 to your computer and use it in GitHub Desktop.
ASP.NET Core - overriding configuration values through environment variables

the appsettings json

  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "SQLServer":
  {
    "Host":"sql123",
    "Port":"1433"
  }
}

The startup file

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(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);
                    config.AddEnvironmentVariables();
                })
                .UseStartup<Startup>();

In the controller

var setting=config.GetValue<string>("SQLServer:Host");

override through environment variable

PS> $env:SQLServer__Host="test"

dotnet run

IIS - use web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\netcoreenvtest.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" >
 <environmentVariables>
        <environmentVariable name="SQLServer__Host" value="PUNKISDEAD" />
      </environmentVariables>
	<aspNetCore/>
  </system.webServer>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment