Disclaimer: I am a consultant at Amazon Web Services, and this is my personal blog. The opinions expressed here are solely mine and do not reflect the views of Amazon Web Services (AWS). Any statements made should not be considered official endorsements or statements by AWS.
In this article, we will understand, how can we read the AppSettings
from appsettings.json
file in ASP.NET Core 3.1.
Step 1: Create a new ASP.NET Core project in Visual Studio 2019.
Step 2: On this screen, you can provide your project name, solution name and location.
Step 3: Here you can select any type of ASP.NET Core Web Application that you want to create. I have selected the API project. This will create an ASP.NET Core Web API application.
Step 4: Open appsettings.json
file. Create an AppSettings
key and provide some key values inside it as I have highlighted in the below picture.
You can also copy the above settings from here.
Step 5: Create a new AppSettings.cs
class file.
Step 6: Add the properties here in this class with the same key names that you have defined in the AppSettings
section of appsettings.json
file.
You can copy the code from here as well for AppSettings.cs
file.
Step 7: Open StartUp.cs
file, and add the highlighted lines in the ConfigureServices
method like below.
Copy the above-highlighted code from here.
The above code does two things. First, it reads the AppSettings
section from the file. Second, it creates a mapping of that with the AppSettings
class and also registers it to be used as IOptions<AppSettings>
using dependency injection.
Step 8: Finally, create a new controller and verify that we can access the AppSettings
values in the code. For this purpose, I have created a new DemoController
, as you can see in the below picture. And I am successfully able to read app settings values in code from appsettings.json
file.
You can copy the above code from here as well.
Thant's all :)
This is how we have successfully read the AppSettings
section from the appsettings.json
file in the ASP.NET Core application.