I need to get the array from the configuration.json file in the asp.net core. I created an API that getting a section from the configuration file but I got nothing. please help me to find out! here is the configuration.json file.
"Settings": {
"Standards": [ "LKG", "UKG", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "COL" ],
"PaymentModes": [ "CASH", "DD", "TRANSFER", "RTGS", "NEFT", "CC", "NB" ],
"FeeTypes": [ "SCHOOL FEE", "HOSTEL FEE", "TRANSPORTATION FEE", "WELCOME PACK FEE", "TOUR FEE", "COACHING FEE", "OTHER FEE" ],
"Installments": [ "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X" ],
"FinancialInstitutes": ["FEDERAL","ICICI","PAYU","AXIS","AXISRTGS","PAYTM"]
}
here is the api.
[HttpGet]
[AllowAnonymous]
[Route("Settings")]
public List<string> GetSettings()
{
var settings = Configuration.GetSection("Settings").Get<List<string>>();
return settings;
}
here is the startup class.
public class Startup
{
private readonly string _contentRootPath;
public IWebHostEnvironment env;
public IConfiguration Configuration { get; }
public Startup(IWebHostEnvironment env)
{
_contentRootPath = env.ContentRootPath;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("configuration.json", optional: true, reloadOnChange: true)
.AddJsonFile($"configuration.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
this.env = env;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfigurationRoot>(provider => { return (IConfigurationRoot)Configuration; }); services.AddMvc()
.AddControllersAsServices();
services.AddHttpContextAccessor();
}
}
I gave singleton dependency to configuration in the startup class and this worked. that was the problem. i just modified my code in which first get all the keys (arrays) and then in the foreach loop i am getting the array's value by the key it gets one by one.
public Dictionary<string, List<string>> GetSettings()
{
var response = new Dictionary<string, List<string>>();
var settings = Configuration.GetSection("Settings").GetChildren().Select(x => x.Key).ToList();
foreach (var setting in settings)
{
response.Add(setting, Configuration.GetSection($"Settings:{setting}").Get<List<string>>());
}
return response;
}