This Microsoft .NET article will explain what appsettings.json is in .NET and C# and how to use it.
The ‘appsettings.json’ file allows us to manage an application configuration securely and efficiently and easily transition between development and production.
Understanding ‘appsettings.json’ in .NET and C#
First introduced in ASP.NET and later in C#, the appsettings.json configuration file uses JSON (JavaScript Object Notation) syntax and holds the application’s configuration. The file’s structure is made of key-value pairs, as shown below.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=mydatabase;User Id=myusername;Password=mypassword;"
},
"AppSettings": {
"ApplicationName": "MyApp",
"Version": "1.0.0"
}
}
In the above example, the configuration is divided into three main sections, Logging
, ConnectionStrings
, and AppSettings
. Each section contains specific settings relevant to different aspects of the application.
How to Use appsettings.json in C#
To use an appsettings.json file in C#, we first need to declare in our Program.cs that we are using the file to read the application’s configuration, as shown in the example below.
// Get config settings from AppSettings
IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
IConfigurationRoot configuration = builder.Build();
string aiSvcEndpoint = configuration["AIServicesEndpoint"];
string aiSvcKey = configuration["AIServicesKey"];
In the example code, we use the configuration builder class and reference the file name.
Add a reference to Project File (.csproj)
For an application to read the configuration from the file, add a reference inside your .csproj file, as shown below to make the file available during runtime.
<!-- Add this ItemGroup to ensure appsettings.json is copied to the output directory -->
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
Below is an example of a project file.
Packages
Depending on your .NET version, you might need to install the following packages and the using statements below.
dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.Json
dotnet add package Microsoft.Extensions.Configuration.Binder
In your Program.cs file, add the following statements.
using System.Text.Json;
using Microsoft.Extensions.Configuration;
Summary
In this post, we explained and showed what ‘appsettings.json’ is and how to use it with a C# application. For more articles about .NET visit our technical blog.
Trackbacks/Pingbacks