Back to: ASP.NET Core Tutorials For Beginners and Professionals
ASP.NET Core AppSettings.json File
In this article, I will discuss the use and importance of the ASP.NET Core AppSettings.json File with Examples. Please read our previous article discussing the ASP.NET Core LaunchSettings.json file in ASP.NET Core with Examples.
What are the Different Configuration Sources Available in the ASP.NET Core application?
If you have worked with earlier versions of ASP.NET, you may be familiar with the web.config file, which was used to store application configuration settings such as database connection strings, API keys, logging details, and global variables.
In ASP.NET Core, we don’t have a web.config file. However, the configuration settings can be provided through various configuration sources, allowing more flexibility and better environment management. Some of these configuration sources are as follows:
- appsettings.json: A JSON file for storing general application settings.
- appsettings.{Environment}.json: Environment-specific JSON files (e.g., appsettings.Development.json, appsettings.Production.json, and appsettings.Staging.json). These override settings in the main appsettings.json file based on the current environment.
- Environment Variables: Values defined in the environment in which the application is running, often used in containerized deployments. In Visual Studio, i.e., in the Development machine, we can achieve the same using launchsettings.json file.
- User Secrets: Used for storing sensitive information in development (e.g., API keys, passwords) without exposing it in source code. It is used during local development. They are not intended for production use.
- Command-line Arguments: Parameters passed when launching the application, which can override settings from all other sources.
What is the ASP.NET Core AppSettings.json File?
The appsettings.json file is a JSON configuration file in ASP.NET Core for storing application-specific settings that can be easily modified without recompiling the application, making the configuration process more dynamic. It provides a structured way to define configuration settings such as:
- Database connection strings
- Logging configuration
- API keys
- Authentication settings
- External API URLs
- Application-level global variables
ASP.NET Core supports environment-specific configuration files (e.g., appsettings.Development.json, appsettings.Staging.json, and appsettings.Production.json). Depending on the application’s environment, these files override the base settings in appsettings.json. This allows us to have different settings for development, staging, and production environments.
When we create an ASP.NET Core Web Application using templates like Empty, Razor Pages, MVC, or Web API, Visual Studio automatically creates an appsettings.json file in the project root directory, as shown in the image below.
Understanding the Structure of appsettings.json
If you open the ASP.NET Core appsettings.json file, you will see the following code by default, which was created by Visual Studio.
This file is typically divided into sections. For example, we might have sections like ConnectionStrings, Logging, or custom sections for our application-specific settings. Now, I will add a key named MyCustomKey within this file. To do so, please modify the appsettings.json file as shown below. As it is a JSON file, we need to store the value as a key-value pair.
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "MyCustomKey": "MyCustomKey Value coming from appsettings.json" }
Logging:
The Logging section configures the application’s logging behavior.
- LogLevel: This subsection specifies the minimum log level for different categories of loggers.
- Default: “Information” – This sets the default log level to Information, meaning logs at the Information level and above (e.g., Warning, Error, Critical) will be recorded.
- Microsoft.AspNetCore: “Warning” – This sets the log level specifically for Microsoft.AspNetCore category to Warning, meaning that only warnings, errors, and critical messages will be logged for components in Microsoft.AspNetCore namespace.
AllowedHosts:
The AllowedHosts section specifies which hosts are allowed to make requests to the application. This is typically used in scenarios where you want to restrict access to certain domains. The “*” wildcard character means that any host is allowed to access the application. You can restrict it by specifying a comma-separated list of allowed hostnames, e.g., “example.com, localhost”.
MyCustomKey:
A custom section that we define for our own application settings. “MyCustomKey”: “MyCustomKey Value coming from appsettings.json”: This is a key-value pair where MyCustomKey is the key, and MyCustomKey Value coming from appsettings.json is the value.
How Do We Access the Configuration Information in ASP.NET Core Application?
ASP.NET Core provides the IConfiguration interface and ConfigurationManager to retrieve settings from appsettings.json and other sources. We can access settings in different parts of the application, such as the Program class or controller actions. Let us see how we can access the MyCustomKey value from the appsettings.json file in our Main method of the Program class. Within the Main method, we will use ConfigurationManager; from controllers and services, we will use the IConfiguration interface.
In the Main Method of the Program Class, the WebApplicationBuilder instance (builder) has a Configuration property that provides access to configuration data from appsettings.json, environment variables, command-line arguments, launchsetting.json, etc. The following are two ways to read configuration data:
Using the GetValue Generic Method:
The GetValue<T>(string key) method allows us to get a value and specify the type, ensuring type safety. We can also provide a default value if the key is not found.
string myCustomKeyValue = builder.Configuration.GetValue<string>(“MyCustomKey”, “DefaultValue”);
Using the ConfigurationManager Indexer:
We can also directly access the configuration value as a string using an indexer. The returned value is always a string, so if you need a different type, you would need to convert it manually.
string myCustomKeyValue = builder.Configuration[“MyCustomKey”];
So, let us modify the Main method of the Program class to access the configuration information from the appsettings.json file.
namespace FirstCoreWebApplication { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); //ConfigurationManager configuration = builder.Configuration; //Get the Configuration Value using Generic GetValue string? MyCustomKeyValue1 = builder.Configuration.GetValue<string>("MyCustomKey", "DefaultValue"); //Get the Configuration Value using Indexer string? MyCustomKeyValue = builder.Configuration["MyCustomKey"]; app.MapGet("/", () => $"{MyCustomKeyValue}"); app.Run(); } } }
Now run the application, and you should see the value as expected in the browser, as shown in the image below.
Note: GetValue<T> is preferred for non-string types, ensuring type safety, while the indexer is suitable for simple string retrieval.
What is the Configuration Execution Order in ASP.NET Core Application?
Before understanding the execution order, let’s have a look at the appsettings.Development.json file. You can find this file within the appsettings.json file of your project as shown in the below image.
Environment-Specific AppSettings.json Files:
ASP.NET Core allows configurations from multiple sources. If the same key is present in multiple configuration sources, the value from the later source will override earlier ones. To understand this, consider the following sources:
- Base appsettings.json: Default configuration.
- Environment-specific appsettings: Overrides settings based on the environment (Development, Staging, or Production).
This means we can have different versions of appsettings.json for different environments, like appsettings.Development.json file for development environment, appsettings.Staging.json file for Staging environment, and appsettings.Production.json file for Production environment.
Now suppose we define MyCustomKey in both appsettings.json and appsettings.Development.json, and run the application in the Development environment, the value from appsettings.Development.json will be used. So, the appropriate file is loaded based on the environment on which the application is running, so that it can read that environment specific settings.
Modify the appsettings.Development.json File.
To better understand the execution order, let us add the same MyCustomKey to this appsettings.Development.json file, which we added to the appsettings.json file. So, modify the appsettings.Development.json file as shown below.Â
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "MyCustomKey": "MyCustomKey Value coming from appsettings.Development.json" }
As you can see, we are using the same key as in the appsettings.json file but with a different value here. Now, set the environment to Development within the launchsettings.json file and run the application. You should get the following output:
As you see, it fetches the MyCustomKey Value from the appsettings.Development.json file. I need to make you clear that if you have a configuration setting in multiple configuration sources with the same configuration key, then the later configuration sources will override the earlier configuration sources.Â
What are the Default Orders for Reading the Configuration Sources in ASP.NET Core?
The default orders in which the various configuration sources are read for the same key are as follows:
- appsettings.json
- appsettings.{Environment}.json
- User Secrets
- Environment Variables
- Command-line Arguments
Using Environment Variables
We already have MyCustomKey in two places, i.e., appsettings.json and appsettings.Development.json. Now add the same key as “MyCustomKey”: “MyCustomKey Value coming from Environment Variable of LaunchSettings.json” in the IIS Express Profile Section of the launchSettings.json file as shown below.
With this change, run the application using the IIS Express launch profile, and it should display the value coming from the environment variable, as shown in the image below.
Using Command Line Argument:
In Visual Studio, we can easily pass command-line arguments to our ASP.NET Core application using the project properties. To do so, right-click on the project in the Solution Explorer and select Properties from the context menu. This opens the project’s properties page.
Go to the Debug tab in the properties window and click on the Open Debug Launch Profiles UI. Look for a section named Command line arguments. This field allows us to specify the arguments the application should receive on startup.
Please enter the command line arguments in this field, for example,–MyCustomKey “MyCustomKey Value coming from Command Line Arguments” as shown in the image below.
Here, –MyCustomKey is the key, and “MyCustomKey Value coming from Command Line Arguments” is the value we pass. Click Save on the toolbar or press Ctrl + S to save the settings. As we are setting the command line arguments for the IIS Express launch profile, so run the application using IIS Express, and you should see the following output:
ASP.NET Core AppSettings.json File Real-Time Examples
The following are some of the real-time examples of how the appsettings.json file can be used in ASP.NET Core applications:
Database Connection Strings:
In this example, a connection string is defined for a database. The application can access this connection string to interact with the database.
{ "ConnectionStrings": { "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;" } }
Logging Configuration
In this example, the logging levels are configured for the application and specific namespaces.
{ "Logging": { "LogLevel": { "Default": "Warning", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } } }
External Service Configuration
This example shows how to store API settings for external services, like base URLs and API keys.
{ "ExternalService": { "BaseUrl": "https://api.example.com/", "ApiKey": "Your-Api-Key-Here" } }
Custom Application Settings
Custom settings specific to the application, like page size for pagination or support email addresses.
{ "ApplicationSettings": { "PageSize": 20, "SupportEmail": "support@example.com" } }
Authentication Settings
Settings related to authentication, like JWT settings in this case.
{ "Authentication": { "Jwt": { "Key": "Your-Secret-Key", "Issuer": "YourIssuer", "Audience": "YourAudience" } } }
In the next article, we will discuss one more important concept, i.e., Middleware Components in ASP.NET Core Applications. In this article, I try to explain the ASP.NET Core AppSettings.json File in detail. I hope this article will help you understand the need for and use of the ASP.NET Core appsettings.json file.
nice article
How i can use the config value anywhere else in the application lets say the controllers or services?
In the controller, you will have to create a constructor that takes IConfiguration interface just as u see above in startup constructor. eg Just imagine you have DefaultController and u need to access config value. You decare a constructor as below
//constructor
public Default()
{
}
here we will have to pass IConfiguration object to constructor (Constructor dependency injection)
public Default(IConfiguration config)
{
}
Now we need to declare a private field that holds this value
private IConfiguration _config;
Now we will assign to _config and everything loos like below
//field
private IConfiguration _config;
//Dependency Injection to inject the Configuration object
public Default(IConfiguration config)
{
_config = config;
}
Now you can access key value like below
var config value = _config[“keyname”];
I suggest you option pattern for that purpose.
Thank you, this is the article I was looking for.