I'm using the .NET Core 1.1 in my API and am struggling with a problem:
appsettings.json
and environment variables.IOptions
.appsettings.json
values.So I do it like this so far:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Something here
services.Configure<ConnectionConfiguration>(options =>
Configuration.GetSection("ConnectionStrings").Bind(options));
// Something there
}
With my appsettings.json
composed like this
{
"ConnectionStrings": {
"ElasticSearchUrl": "http://localhost:4200",
"ElasticSearchIndexName": "myindex",
"PgSqlConnectionString": "blablabla"
}
}
I get all the configurations mapped to my class ConnectionConfiguration.cs
. But I cannot get the environment variables to be mapped as well. I tried the names like: ConnectionStrings:ElasticSearchUrl
, ElasticSearchUrl
, even tried specifying the prefix to .AddEnvironmentVariables("ConnectionStrings")
without any result.
How should I name the environment variables so it can be mapped with services.Configure<TConfiguration>()
?
The GetEnvironmentVariable(String) method retrieves an environment variable from the environment block of the current process only. It is equivalent to calling the GetEnvironmentVariable(String, EnvironmentVariableTarget) method with a target value of EnvironmentVariableTarget.
To set the ASPNETCORE_ENVIRONMENT environment variable in Windows: Command line - setx ASPNETCORE_ENVIRONMENT "Development" PowerShell - $Env:ASPNETCORE_ENVIRONMENT = "Development"
Application configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings. json.
The
:
separator doesn't work with environment variable hierarchical keys on all platforms.__
, the double underscore, is supported by all platforms and it is automatically replaced by a:
Try to name the environment variable like so ConnectionStrings__ElasticSearchUrl
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With