Skip to content

Instantly share code, notes, and snippets.

@thanley11
Last active February 13, 2019 16:52
Show Gist options
  • Save thanley11/ae256f9c94f34e68f7fe78f3b652eb04 to your computer and use it in GitHub Desktop.
Save thanley11/ae256f9c94f34e68f7fe78f3b652eb04 to your computer and use it in GitHub Desktop.
Dot net core configuration setup

How to use config in dot net core

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": "..."
    }
}

Untyped retrieval example

{
  "AppSettings": {
        "token": "1234"
    }
}
 var token = Configuration.GetSection("AppSettings:token");

More advanced

 "Serilog": {
        "WriteTo": [
            {
                "Name": "File",
                "Args": { "path": "%TEMP%\\Logs\\serilog-configuration-sample.txt" }
            }
        ]
    }
  1. You need to use the index in the environment variable for arrays
name value
Serilog:WriteTo:0:Args:path %TEMP%\\customPath

Using Secrets

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]"
}

Access the secret

if (env.IsDevelopment())
    {
        builder.AddUserSecrets<Startup>();
    }
public void ConfigureServices(IServiceCollection services)
    {
        _moviesApiKey = Configuration["Movies:ServiceApiKey"];
    }

Typed config in DotNetCore

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;
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment