Skip to content

Application settings in ASP.NET Core

Application settings is used to configure your application in ASP.NET Core. Application settings is key-value pairs that can be read by configuration providers. Examples of configuration variables is a connection string to a database, an api endpoint or the duration for data to be stored in cache.

Application settings can be different depending on the environment, development settings can be different from production settings. You can use different configuration files depending on the environment or set environment variables in your production environment (Appsettings in Azure portal for example) that overrides your development settings.

Build configuration

You need to build your configuration in ASP.NET Core 1.X and in projects that not is web applications. User secrets is application settings stored outside of your project, you can create a secret.json file by right-clicking on your project in Visual Studio and click on Manage User Secrets (only web applications).

public IConfigurationRoot configuration { get; }

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

    if (env.IsDevelopment())
    {
        builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables(); // Important to set Azure portal variables
    configuration = builder.Build();
}

In this configuration build you can see that the configuration first is built from a appsettings.json file. Settings might be overwritten by appsettings.Development.json or user secrets (secrets.json). Environment variables is added last and these variables might overwrite settings that was set before.

Web application entry point

When you create a new web application in ASP.NET Core 2.X, there is no need to build configuration because it is built for you. You can add your own configuration in ConfigureAppConfiguration if you want, this is the place to add Azure Key Vault settings also.

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();

    } // End of the main method

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseApplicationInsights()
        .ConfigureAppConfiguration((context, config) =>
        {
            config.Sources.Clear();
            config.AddJsonFile("myconfig.json", optional: true);
        })
        .UseStartup<Startup>();

} // End of the class

File to model

When the configuration is built in your ASP.NET Core project, you can get these settings directly or convert them to a model. This is an example of an appsettings.json file.

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Information"
    }
  },
  "FortnoxOptions": {
    "ClientId": "",
    "ClientSecret": "",
    "AuthorizationCode": "",
    "AccessToken": ""
  }
}

You can create a FortnoxOptions model to easily convert these settings in the StartUp class. If you want to override ClientId in FortnoxOptions as an environment variable in Azure portal, you need to set the key to FortnoxOptions:ClientId.

public class FortnoxOptions
{
    #region Variables

    public string ClientId { get; set; }
    public string ClientSecret { get; set; }
    public string AuthorizationCode { get; set; }
    public string AccessToken { get; set; }

    #endregion

    #region Constructors

    public FortnoxOptions()
    {
        // Set values for instance variables
        this.ClientId = "";
        this.ClientSecret = "";
        this.AuthorizationCode = "";
        this.AccessToken = "";

    } // End of the constructor

    #endregion

} // End of the class

StartUp

Your configuration is managed in the StartUp class, this is where you convert settings to models. The contents below shows how to register IOptions by getting values from configuration or just convert configuration to a model.

public IConfiguration configuration { get; set; }

public Startup(IConfiguration configuration)
{
    this.configuration = configuration;

} // End of the constructor

public void ConfigureServices(IServiceCollection services)
{
    // Add the mvc framework
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    // Register options
    services.Configure<FortnoxOptions>(configuration.GetSection("FortnoxOptions"));
    services.Configure<BlobStorageOptions>(configuration.GetSection("BlobStorageOptions"));
    services.Configure<TableStorageOptions>(configuration.GetSection("TableStorageOptions"));
    services.Configure<CacheOptions>(options => { options.ExpirationInMinutes = 240d; });

    // Add redis distributed cache
    if (configuration.GetSection("RedisCacheOptions")["ConnectionString"] != "")
    {
        services.AddDistributedRedisCache(options =>
        {
            options.Configuration = configuration.GetSection("RedisCacheOptions")["ConnectionString"];
            options.InstanceName = "Doxservr:";
        });
    }

} // End of the ConfigureServices method

Azure Key Vault

You can use Azure Key Vault to store application settings and certificates (SSL/TLS for example). You need to install a NuGet package called Microsoft.Extensions.Configuration.AzureKeyVault and add these settings in the CreateWebHostBuilder method of the Program class.

.ConfigureAppConfiguration((context, config) =>
{
	var builtConfig = config.Build();

	config.AddAzureKeyVault(
		$"https://mysite.vault.azure.net/",
		"ClientId",
		"ClientSecret",
		new KeyVaultSecretManager());
})

We have used a KeyVaultSecretManager class to build configuration from Azure Key Vault. KeyVault is the identifier, to get a configuration value you just have to set the section-key to KeyVault (configuration.GetSection(“KeyVault”)[“A_KEY_IN_AZURE_KEY_VAULT”]).

public class KeyVaultSecretManager : IKeyVaultSecretManager
{
    public bool Load(SecretItem secret)
    {
        return true;
    }

    public string GetKey(SecretBundle secret)
    {
        return $"KeyVault:{secret.SecretIdentifier.Name}";
    }

} // End of the class

Leave a Reply

Your email address will not be published. Required fields are marked *