How to read appsettings.json in .NET Core Controller file

Updated on: May 26, 2021

We are storing application settings in .NET Core in appsettings.json file, sometimes you need to read the appsettings in your Controller file and use it for specific purpose such as Passing Database Connection string, passing email id or password, the following steps shows to read and use settings from appsettings.json file in .NET Core MVC or Web API Controller file:

Step 1: Create the .NET Core Web Application (MVC or Web API) using Visual Studio or through .NET CLI command as shown below:

dotnet new mvc -o NetCoreMVCApp1

From Visual Studio => Create a New Project => Select "ASP.NET Core Web App (Model-View-Controller) template and click on Next button => Give Project Name "NetCoreMVCApp1" and click on Next button => select the Target Framework and Authentication Type and click on Create button to create the .NET Core MVC application.

Step 2: Once application is created, open appsettings.json file in Visual Studio and add the below code:

  1. {
  2.   "MySettings": {
  3.     "Username":"Test username"
  4.   }
  5. }

Step 3: Open HomeController.cs file and add the below code to read the settings from appsettings.json file and use it:

  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.Extensions.Configuration;

  3. namespace NetCoreMVCApp1.Controllers
  4. {
  5.     public class HomeController : Controller
  6.     {
  7.         private readonly IConfiguration _config;
  8.         public HomeController(IConfiguration configuration)
  9.         {
  10.             _config = configuration;
  11.         }

  12.         public IActionResult Index()
  13.         {
  14.             ViewBag.TestUsername = _config["MySettings:Username"];
  15.             return View();
  16.         }
  17.     }
  18. }

In the above code, we have added IConfiguration in the HomeController constructor and used in the Index() Action Method.

Step 4: Now, we will use this appsettings in the Index.cshtml page as shown below:

  1. @{
  2.     ViewData["Title"] = "Home Page";
  3. }

  4. <div class="text-center">
  5.     <h2>Test Usename: @ViewBag.TestUsername</h2>
  6. </div>

Step 5: We will now run the application to see the appsettings output on the HomeController=>Index page:

You can follow the above steps to read the appsettings from appsettings.json file and use it in the Controller class. We have used inbuilt Constructor Dependency Injection feature provided by .NET Core to use IConfiguration which represents application's key/value configuration properties.