Vadim Peretokin
Vadim Peretokin

Reputation: 2826

What is the .NET Core way of storing application settings?

I'm developing a cross-platform (win/mac/linux) application and I'm looking to store my application state. What is the .NET Core recommended way of doing this?

I've dug through the documentation and the closest thing I found was this, which is aimed at Visual Studio/.NET Framework (and I'm on VS Code).

Upvotes: 8

Views: 4186

Answers (3)

Prakash G. R.
Prakash G. R.

Reputation: 4892

You can use the ConfigurationBuilder from the Microsoft.Extensions.Configuration nuget package

Although the docs are for ASP Core, you should be able to use them in your regular .Net Core app.

Create settings.json:

{
    "mysetting": "value",
}

And use it:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("settings.json")
    .Build();

// get the values from the settings.json
var mySetting = configuration["mysetting"];
Console.WriteLine(mySetting);

Upvotes: 0

Nicholas
Nicholas

Reputation: 1980

There are 3 ways,

  1. ONLY For Localhost

Simply stash them in your appsettings.json or as environment variables.

For Staging / Production,

  1. Azure Key Vault

By utilising Azure Key Vault and the Microsoft.Extensions.Configuration.AzureKeyVault NuGet Package, you will be able to stash configurations for your projects in the best way possible in the actual environment.

You then simply inject it in,

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
 WebHost.CreateDefaultBuilder(args)
 .ConfigureAppConfiguration((context, config) =>
 {
     var root = config.Build();
     config.AddAzureKeyVault(
        $”https://{root["KeyVault:Vault"]}.vault.azure.net/",
        root[“KeyVault:ClientId”],
        root[“KeyVault:ClientSecret”]);
 })
 .UseStartup<Startup>();

Although you still have to stash those 3 variables in, Azure has Azure AD to enforce access only to specified Applications. Thus, you need to register an application under the Azure AD in order for this to work. There are also restrictive features that will help you sandbox Azure Key Vault further.

  1. Existing Vault Storages

Last but not least, the last way is to utilise existing vault storage options like HashiCorp. Libraries like https://github.com/rajanadar/VaultSharp will help you to implement it quickly and effectively. This is suitable for you if you primarily use a non-Azure provider for your servers.

Upvotes: 1

Alsein
Alsein

Reputation: 4775

As described here, you can use appsettings.json, which is generated and referenced within the new project template in dotnet new command

Upvotes: 0

Related Questions