How to read values from appsettings.json in Asp.Net Core

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.

In this tutorial, I will write all these constants on appsetting.json file and later read these values whenever I need them from the mailcontroller.

There are two options.

Option 1:

Create a POCO class that represent the mailConfig section on appsettings.json.

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 mailcontroller.cs

You have the another approach too to implement the same.

Option 2:

Everything is same up to the creation of POCO class. In ConfigureServices() method, we register the configuration with singleton instead of Configure() method.

The constructor injection on the controller is clean unlike the first option. You don’t need to bother with IOptions<T> which somehow makes it even more simple.

Simple huh ??

Thanks for passing by.

About dipneupane

Dip is a passionate Software Developer based in Kathmandu, Nepal. He chew code and smash keyboard for living. Apart from that, he writes about almost everything on buzzedcode.com.

View all posts by dipneupane →

2 Comments on “How to read values from appsettings.json in Asp.Net Core”

  1. Appreciate the post. One critique I would make.
    “Hard-coding them whenever and wherever we need it is always a bad practice on application development.”
    Actually this is not 100% true. The nature of a constant is to not change. So hard coding a constant is perfectly acceptable (as long as it is explicitly defined as such for proper form). Big G (the universal gravitational constant) does not change. The universe depends on this fact. Configuration items are not constants, they are variables. So I think that distinction needs to be made clear. Appsettings should not be a place for “constants”.

    1. Just for clarity, instead of hard-code, I would prefer the term “define” constants. Agree that coding literal constants within code is not a good practice. But defining a constant in code is perfectly fine.

Leave a Reply

Your email address will not be published. Required fields are marked *