Trying to configure custom JSON file and map it to the related Data Model. Able to make it work at the class level but trying to achieve the same in the startup. I'd highly appreciate your help. Thanks.
// This works.
Class A
public static string GetData(string name)
{
var jsonFile = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, $"customSettings.json"););
var res = JsonConvert.DeserializeObject<Formats>(jsonFile);
}
Trying to achieve the following i.e., map CustomSettings.json to Formats in the Startup.cs and pass it as a scoped object.
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// this field is from appsettings.json.
services.Configure<AppDM>(Configuration.GetSection("SomConfigFrom_appsettings"));
// custom mapping : customSettings.json
services.Configure<Formats>(Configuration.
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
....
}
customSettings.json
{
"Formats": [
{
"Name": "FormatA"
}
]
class AppDM
{
string a { get; set; }
}
class Formats
{
string Name { get; set; }
}
Step 1
To add an additional JSON file in configuration, add the below line:
In Program.cs as below:
Step 2
From the attached JSON file, the
Formatsis an array of objects. It should be read asList<FormatConfig>type.In Startup.cs,
Step 3
In YourController.cs, get the configuration dependency,
IOptions<List<FormatConfig>>via constructor injection as below:Reference
JSON configuration provider - Configuration in ASP.NET Core