Needless to say, almost every application has to deal with some configurations. There are tons of use cases, and you already have a few of them in mind, don’t you?
If you work with .NET, you’ve probably already used appssettings.json file. This is a good starting point, but may not be sufficient in the case of complex applications (and complex deployments).
In this article we will learn some ways to configure configurations in a .NET API application. we will use App settings file, of course, and some other ways such as dotnet CLI. let’s go! 🚀
Project definition
First things first: let’s set up the demo project.
I created a simple .NET 6 API implementation using minimal APIs. This is my entire app (yes, less than 50 lines!)
using Microsoft.Extensions.Options;
namespace HowToSetConfigurations
{
public class Program
{
public static void Main(string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<MyRootConfig>(
builder.Configuration.GetSection("RootConfig")
);
builder.Services.Configure<JsonOptions>(o =>
{
o.SerializerOptions.WriteIndented = true;
});
WebApplication app = builder.Build();
app.MapGet("/config", (IOptionsSnapshot<MyRootConfig> options) =>
{
MyRootConfig config = options.Value;
return config;
});
app.Run();
}
}
public class MyRootConfig
{
public MyNestedConfig Nested { get; set; }
public string MyName { get; set; }
}
public class MyNestedConfig
{
public int Skip { get; set; }
public int Limit { get; set; }
}
}
nothing else! 🤩
In short, I scaffold you WebApplicationBuilder
Define that I want to map the settings section with the root name RootConfig to my class MyRootConfig
and then launch the application.
I then expose a single endpoint, /configwhich returns the current configurations, wrapped in IOptionsSnapshot<MyRootConfig>
resist.
Where is the app’s configuration source?
As stated on the Microsoft docs website, here 🔗God WebApplicationBuilder
…
Loads the app configuration in the following order from: appsettings.json. App settings. {Environment}.json. User secrets when the application is running in the development environment using the login assembly. Environment Variables. Command line arguments.
So, yes, we have several possible sources, and the order does matter.
Let’s see a bunch of them.
Configure settings within the appsetting.json file
The most common way is using appssettings.json file. here, b structured and hierarchical wayYou can define all the logs that are used as the basis of your application.
A typical example is this:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"RootConfig": {
"MyName": "Davide",
"Nested": {
"Skip": 2,
"Limit": 3
}
}
}
With this file, all fields in RootConfig The element will be mapped to MyRootConfig
class at startup. This object can then be returned using the /config endpoint.
Running the application (using Visual Studio or dotnet CLI) you can call this endpoint and see the expected result.
Use an environment-specific appsettings.json
Now, you probably know you can use another App settings Files with a name such as appssettings.Development.json.
With this file, you can override specific configurations using the same structure, but ignore any settings that don’t need to be changed.
Let’s update you limit A field defined in the “base” application settings. You don’t have to recreate the whole structure just for one key; You can use this JSON instead:
{
"RootConfig": {
"Nested": {
"Limit": 9
}
}
}
Now if we run the application using VS we will see this result:
ok but What made .NET understand that I want to use this file?? It’s a matter of Environment Variables and Activate profiles.
How to set profiles in the launchSettings.json file
Inside the Properties folder in your project, you can see a launchSettings.json file. As you might expect, the file describes how to run the application.
Here we have several launch profiles, and each one specifies ASPNETCORE_ENVIRONMENT
variable. By default, its value is set to development.
"profiles": {
"HowToSetConfigurations": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "config",
"applicationUrl": "https://localhost:7280;http://localhost:5280",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
}
Now, remember that the environment is specific App settings The file name is set to App settings. {Environment}.json. Therefore, by running your application with Visual Studio using HowToSetConfigurations launch profile, you’ll replace it {around the} With developmentthus using appssettings.Development.json.
Ça va sans dire which you can use any value you prefer – such as Staging, MyCustomEnvironmentName, and so on.
How to set the current environment with the CLI
If you are using the dotnet CLI You can set the environment variable as
dotnet run --ASPNETCORE_ENVIRONMENT=Development
Or, more simply, you can use
dotnet run --environment Development
and get the same result.
How are nested configurations resolved?
As we saw in a previous article, even if we use configurations defined in a hierarchical structure, in the end, they become key-value pairs.
God limit key as defined here:
{
"RootConfig": {
"Nested": {
"Limit": 9
}
}
}
transform to
{
"Key": "RootConfig:Nested:Limit",
"Value": "9"
},
with the :
separator. We will use this information soon.
Set configurations in the launchSettings file
As we saw before, each profile defined in the launchSettings file describes a list of environment variables:
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
This means we can also set our configurations here, and load them when using this particular profile.
of these configurations
"RootConfig": {
"MyName": "Davide",
"Nested": {
"Skip": 2,
"Limit": 3
}
}
I want to update you My name field.
I can then update the current profile as such:
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"RootConfig:MyName": "Mr Bellone"
}
So when I run the app using this profile, I get the following result:
You noticed the key RootConfig:MyName
? 😉
🔎 Note that we now have both My name = Mr. Balloonas defined in the lauchSettings file, and Limit = 9Since we still use appssettings.Development.json file (that’s why “ASPNETCORE_ENVIRONMENT”: “Development” ).
How to set the current profile with the CLI
Obviously we can use the dotnet CLI to load the entire environment profile. We just need to denote it using the --launch-profile
flag:
dotnet run --launch-profile=HowToSetConfigurations
Configure application settings using the dotnet CLI
Finally, we can specify configuration values directly using the CLI.
It’s just a matter of specifying key-value pairs like this:
dotnet run --RootConfig:Nested:Skip=55
and also – Ta Da! – Look at this result:
❓ A question for you! Note that although I only specified the Skip value, both Limit and MyName have the value set earlier. Do you know why this happens? Comment below if you know the answer! 📩
Additional readings
As always, there’s more!
If you want to know more about how dotNET APIs are loaded and started, you should check out this page:
🔗 ASP.NET Core Web Host | Microsoft Docs
Okay, now you know different approaches to setting up configurations. How do you know the exact values defined in your application?
🔗 The 2 secret endpoints I create in my .NET APIs | Code4IT
This article first appeared on Code4IT
finishing
Okay, so in this article we’ve seen different approaches you can use to configure configurations in your .NET API projects.
Knowing what you can do with the CLI can be especially helpful when using CI/CD, in case you need to run the application using specific keys.
Do you know of other ways to configure settings?
Happy coding!
🐧
.