Read Values from appsettings.json in ASP.NET Core
The appsettings.json file in ASP.NET Core contains all application settings. This blog will show you how to get the values from appsettings.json
The following is an example of appsettings.json configuration. I have added a Sample setting here. It has two settings: AppName and Auth.The Auth setting contains Username and Password.
appsettings.json"Sample": {
"AppName": "SampleApp",
"Auth": {
"Username": "Parker",
"Password": "$@M9l3"
}
}
There are several methods for obtaining appsettings values. Let's go through them one by one.
Method 1:
Here the IConfiguration is injected to the HomeController constructor. Then using the GetValue<T> method the setting values are collected. The values are retrieved using the key.
HomeController.cs{
private readonly IConfiguration _config;
public HomeController(IConfiguration config)
{
_config = config;
}
public IActionResult Index()
{
var appName = _config.GetValue<string>("Sample:AppName");
var userName = _config.GetValue<string>("Sample:Auth:Username");
var password = _config.GetValue<string>("Sample:Auth:Password");
return View();
}
}
Method 2:
The second way to extract values from the appsettings.json file is as follows. In order to obtain values, the model class was first created. The first one is called Sample, and the second is called SampleAuth.
Sample.cs{
public string AppName { get; set; }
public SampleAuth Auth { get; set; }
}
public class SampleAuth
{
public string Username { get; set; }
public string Password { get; set; }
}
IConfiguration has also been used in this case. In this case, a configuration sub-section with the specified key can be obtained using the GetSection method.
HomeController.cs{
var sample = _config.GetSection("Sample").Get<Sample>();
return View();
}
Method 3:
The options pattern is used to read the values in this procedure. The configuration instance has been registered in the program.cs file.
program.cs………
builder.Services.Configure<Sample>(builder.Configuration.GetSection("Sample"));
// Add services to the container.
builder.Services.AddControllersWithViews();
………
The following is a HomeController code. The IOptions<Sample> is injected into the HomeController constructor here. To access the values, you can inject the IOptions<Sample>anywhere.
HomeController.cs{
private readonly Sample _sample;
public HomeController(IOptions<Sample> options)
{
_sample = options.Value;
}
public IActionResult Index()
{
var sample = _sample;
return View();
}
}
I hope this helps you. Keep coding.
Comments
Post a Comment