How to read appsettings.json in .NET Core Controller file
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:
- {
- "MySettings": {
- "Username":"Test username"
- }
- }
Step 3: Open HomeController.cs file and add the below code to read the settings from appsettings.json file and use it:
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- namespace NetCoreMVCApp1.Controllers
- {
- public class HomeController : Controller
- {
- private readonly IConfiguration _config;
- public HomeController(IConfiguration configuration)
- {
- _config = configuration;
- }
- public IActionResult Index()
- {
- ViewBag.TestUsername = _config["MySettings:Username"];
- return View();
- }
- }
- }
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:
- @{
- ViewData["Title"] = "Home Page";
- }
- <div class="text-center">
- <h2>Test Usename: @ViewBag.TestUsername</h2>
- </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.