I'm working on .net core api and need to get values from appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"projectList": "Project",
"projectCatList": "Project Categories",
}
}
}
I want to access these vaues in controller class and another .cs class

Jignesh KumarPosted Nov 6, 2022, 4:09 AM
Hi Ritu,
You need to inject IConfiguration interface in which ever place you need to use. After that you can get values from appsetting.json file,
Please refer this link which will help you out,
https://www.c-sharpcorner.com/article/reading-values-from-appsettings-json-in-asp-net-core/
https://www.c-sharpcorner.com/article/appsettings-6-ways-to-read-the-config-in-asp-net-core-3-0/
Jaydeep PatilPosted Nov 5, 2022, 5:27 AM
You can simply inject IConfiguration inside the constructor of the particular class and use that object to get environment variables value form appsettings.json
RituPosted Nov 4, 2022, 9:51 AM
thanks for ur solution
but when i'm using this approach to my code like below:
public class TeemController : ControllerBase
{
public readonly IConfiguration _iconfiguration;
public TeemController(IConfiguration iconfiguration)
{
_iconfiguration = iconfiguration;
}
[HttpGet("getTime")]
public ActionResult getTime(string r, string p, string e)("DevSetting:pr");
{
string p = _iconfiguration.GetValue
PContract pCon = getP() ;
//.....
}
} // it shows p value successfully.
-----------------------------------------------------------------------
But when i'm using this approach to another class
it throws error null reference
public class MyHelper getP() ("DevSetting:pr");
{
public static IConfiguration _iconfiguration;
public MyHelper(IConfiguration iconfiguration)
{
_iconfiguration = iconfiguration;
}
private static List
{
string p = _iconfiguration.GetSection("DevSetting").GetSection("pr").Value;
string p = _iconfiguration.GetValue
//......
}
Rijwan AnsariPosted Nov 3, 2022, 2:07 PM
You can do in controller or class.
First inject IConfiguration in Ctor as shown:
Then use configuration as in any Action as shown:
You can do the same way in class. However, if it better to use interface and implementation.
https://www.c-sharpcorner.com/article/appsettings-6-ways-to-read-the-config-in-asp-net-core-3-0/
Vishal YelvePosted Nov 3, 2022, 2:04 PM
Refer links
https://www.c-sharpcorner.com/article/reading-values-from-appsettings-json-in-asp-net-core/