Reading Values From Appsettings.json In ASP.NET Core
I have added the following JSON object in the appsetting.json file.
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "credentials": { "UserName": "Shubham", "Password": "code2night", "Email": "code2night@gmail.com" } }
We will create a model class in which we will define properties with the same name as we have defined in our appsettings.json, Create a class inside the model folder
public class CredSettingsModel { public string UserName { get; set; } public string Password { get; set; } public string Email { get; set; } }
Go to Program.cs file and we will register our class by writing the below code.
builder.Services.Configure<CredSettingsModel>(builder.Configuration.GetSection("credentials"));
Then we can inject it into our HomeController constructor using our IOptions instance.
using ConfigrationManager.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System.Diagnostics; namespace ConfigrationManager.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; protected readonly IConfiguration _configuration; private readonly CredSettingsModel _credSettingsModel; public HomeController(ILogger<HomeController> logger, IOptions<CredSettingsModel> options) { _logger = logger; _credSettingsModel = options.Value; } public IActionResult Index() { string UserName = _credSettingsModel.UserName; string Password = _credSettingsModel.Password; string Email = _credSettingsModel.Email; return View(); } } }
Run the project and see the output it will show the username which we mentioned in the appsetting.json file