Posts Tagged config

How to read config settings in Asp.Net Core

Introduction

In this article I will explain the details of how to read config settings in Asp.Net Core.

Description

In Asp.Net webforms we used web.config file to store the config values like a connection string, appsettings etc.However, in Asp.Net core, the config file doesn’t exist anymore.  Instead, we have a slightly different approach where the configuration API provides a way of configuring an app based on a list of name-value pairs that can be read at runtime from multiple sources. You can read the config values from multiple sources like JSON, XML etc.

In this article we will examine how to implement config files based on JSON formats in Asp.Net Core application.

Add the Required references

To read the values from appsettings.json, we need to add the below references to project

Add appsettings.json file to store config values

We will store the config items as Name:Value pair in this json file.  You can also add hierarchical list in json file where each items will be separated by comma.

Sample value

Create ConfigurationBuilder in Startup.cs class

We use AddJsonFile” method in JsonConfigurationExtensions class to provide the Json File path. To reload the configuration file if the file changes we can set the reloadOnChange property.  You can find details of AddJsonFile method here.

Read the value from appsetttings.json file

Using the GetSection method we can access the values from appsettings.json file

Complete Code

You can find the complete source code for this article here

Advertisements

, , ,

Leave a comment