Configuration Data in ASP.NET Core

 

Depending on your context you may not want to be storing these types of application settings in configuration files that are committed to source control.

As you would expect, my local environment for development and once I deploy to Azure have completely different configurations.

So how do you change the configuration from local to production?

If you are used to using appSettings from the app.config and web.config, you may have been going down the road of transforming and replacing values with tools

With ASP.NET Configurations, there’s a new way to do this.

Configuration

ASP.NET Core has a ConfigurationBuilder that enables you to load application settings from various places.  If you’ve loaded up a brand new ASP.NET Core app, you’re Startup looks something like this.

You have a new appsettings.json file you can use as well as an optional appsettings for each different environment.

I could use the appsettings.Development.json for local development, however as mentioned i want to keep sensitive data out of this file.

For this, I’ve now been using User Secrets.

User Secrets

ASP.NET Core adds a new way to store your sensitive data with User Secrets.

User Secrets are simply a plain text json file that are stored in your systems user profile directory.  Meaning the file is stored outside of your project directory.

There are a couple ways to manage your user secrets, first you need to add Microsoft.Extensions.SecretManager.Tools in the tools section of your project.json.

hflnet52

I’m unaware of how this translates to the new .csproj format.

If you are using the dotnet CLI, then you should now be able to run dotnet user-secrets –version

Next in your project.json you want to add a “userSecretsId” property in the root.  The value can be anything you want but should probably keep it unique so it doesn’t collide with another user secrets you create for any other project.

In order to load the secrets file, you need to first add Microsoft.Extensions.Configuration.UserSecrets package in your project.json

As mentioned, since I only use user secrets for local development, we can now load the secrets using the ConfigurationBuilder in our Startup

Visual Studio

If you are using Visual Studio, you can edit your user secrets file by accessing it in the context menu of your project in the solution explorer.

vbbb

CLI

If you are using the dotnet CLI then you can call dotnet user-secrets [options] [command] to clear, list, remove and set secrets.cli

Example

Simple example would be wanting to store the connection string to a database.

dotnet user-secrets set ConnStr “User ID=Derek;Password=CodeOpinion;”

Now within our code we can access the connection string after we built our configuration from the ConfigurationBuilder.

Production

Next post I’ll take a look at how you can use Environment Variables and specifically how to set them when deploying as an App Service within Azure.