In this article we will learn how to read values from appsettings.json in Asp.Net Core. In ASP .NET application we store key and values are in web.config file but in ASP .NET Core it is recommended that all the key values are stored in appsettings.json of connection string and configuration files etc.

There is a simple approach to read values from appsettings.json file in AspNet Core. We write our custom configuration on appsetting.json file available on the root folder of the project.

Why do we need custom configuration?

In an application, there are some constants that need to be used throughout the application. Hard-coding them whenever and wherever we need it is always a bad practice on application development.
So, maintaining all these constants from the single place helps to create a maintainable software solution.

Sending an email is the basic feature which takes some parameters like hostname, port-no, password, company-email etc which doesn’t change frequently.
There are two ways to read the file of appsetting.json.
First Way
In ConfigureServices() method, we register the configuration with singleton instead of Configure() method.
Create a mailConfig class that hold the appsettings.json information. The constructor injection on the controller of MailController

Second Way
Register the configuration on ConfigureServices() method of Startup.cs class. The appsettings.json may consist many sections based on the requirement of the project. Notice that “mailConfig” on GetSection() method represents the section name.

Now we inject the  IOptions<T> on the constructor of the Homecontroller.cs

You can see all the mail configs are read from appsettings.json

</> Find the Source Code in

 In this tutorial How to read values from appsettings.json in Asp.Net Core. If have any question related to this topic then give your feedback.

Post a Comment

Previous Post Next Post