Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load appsetting.json section into Dictionary in .NET Core?

I am familiar w/ loading an appsettings.json section into a strongly typed object in .NET Core startup.cs. For example:

public class CustomSection  {    public int A {get;set;}    public int B {get;set;} }  //In Startup.cs services.Configure<CustomSection>(Configuration.GetSection("CustomSection"));  //Inject an IOptions instance public HomeController(IOptions<CustomSection> options)  {     var settings = options.Value; } 

I have an appsettings.json section who's key/value pairs will vary in number and name over time. Therefore, it's not practical to hard code property names in a class since new key/value pairs would require a code change in the class. A small sample of some key/value pairs:

"MobileConfigInfo": {     "appointment-confirmed": "We've booked your appointment. See you soon!",     "appointments-book": "New Appointment",     "appointments-null": "We could not locate any upcoming appointments for you.",     "availability-null": "Sorry, there are no available times on this date. Please try another." } 

Is there a way to load this data into a MobileConfigInfo Dictionary object and then use the IOptions pattern to inject MobileConfigInfo into a controller?

like image 384
ChrisP Avatar asked Mar 16 '17 22:03

ChrisP


People also ask

What is Appsetting json in ASP.NET Core?

The appsettings. json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information.


1 Answers

Go with this structure format:

"MobileConfigInfo": {     "Values": {        "appointment-confirmed": "We've booked your appointment. See you soon!",        "appointments-book": "New Appointment",        "appointments-null": "We could not locate any upcoming appointments for you.",        "availability-null": "Sorry, there are no available times on this date. Please try another."  } } 

Make your setting class look like this:

public class CustomSection  {    public Dictionary<string, string> Values {get;set;} } 

then do this

services.Configure<CustomSection>((settings) => {      Configuration.GetSection("MobileConfigInfo").Bind(settings); }); 
like image 79
code5 Avatar answered Sep 28 '22 02:09

code5