This env variable determines which appsettings.json file is used
name | value |
---|---|
ASPNETCORE_ENVIRONMENT | Development |
If set to Development
, it will use the values from appsettings.Development.json
If set to Production
, it will use the values from appsettings.json
If set to Foo
, it will use the values from appsettings.Foo.json
Example appsettings.json format
{
"Config": {
"ApplicationName": "MyApp",
"Version": "10"
}
}
If you set env variables in your system level environment variables, use this format (using colons):
name | value |
---|---|
Config:ApplicationName | AppName2 |
Config:Version | 13 |
Note: You will need to restart Visual Studio when you add a new environment variable in order for it to be recognized
Note: Other environments (linux, mac) use _
and __
to show heirarchy
ASPNETCORE_My__Settings
=
{
"my": {
"settings": "..."
}
}
{
"AppSettings": {
"token": "1234"
}
}
var token = Configuration.GetSection("AppSettings:token");
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": { "path": "%TEMP%\\Logs\\serilog-configuration-sample.txt" }
}
]
}
- You need to use the
index
in the environment variable for arrays
name | value |
---|---|
Serilog:WriteTo:0:Args:path |
%TEMP%\\customPath |
Anything that is sensitive (connection string passwords, api keys) should be kept in secrets.
Right click the project in Visual Studio and select
Manage User Secrets
This creates a node in the csproj file called:
<PropertyGroup>
<UserSecretsId>[guid]</UserSecretsId>
</PropertyGroup>
The secrets file is kept here:
C:\Users\[Username]\AppData\Roaming\Microsoft\UserSecrets\[guid]
You would write the secrets in flattened form to overwrite the appsettings values:
{
"Serilog:WriteTo:1:Args:splunkHost": "[your url]",
"Serilog:WriteTo:1:Args:eventCollectorToken": "[your apiKey]"
}
if (env.IsDevelopment())
{
builder.AddUserSecrets<Startup>();
}
public void ConfigureServices(IServiceCollection services)
{
_moviesApiKey = Configuration["Movies:ServiceApiKey"];
}
Create a Config model
public class Config
{
public string ApplicationName { get; set; }
public int Version { get; set; }
}
In Startup.cs
public Startup(IHostingEnvironment env, IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<Config>(Configuration.GetSection("Config"));
// Can access secrets also
// services.Configure<Models.Serilog>(Configuration.GetSection("Serilog"));
}
In Controllers
using Microsoft.Extensions.Options;
public class LogController : Controller
{
private readonly IOptions<Config> _config;
public LogController( IOptions<Config> config)
{
_config = config;
}
[HttpGet]
public IEnumerable<string> Get()
{
Console.WriteLine(_config.Value.ApplicationName);
return;
}
}