Home > database >  ASP.NET Core 3.1 - Configure custom JSON in Startup
ASP.NET Core 3.1 - Configure custom JSON in Startup

Time:08-20

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; }
}

CodePudding user response:

Step 1

To add an additional JSON file in configuration, add the below line:

.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.AddJsonFile("customSettings.json", optional: true, reloadOnChange: true);
})

In Program.cs as below:

using System.IO;

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddJsonFile("customSettings.json", optional: true, reloadOnChange: true);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Step 2

From the attached JSON file, the Formats is an array of objects. It should be read as List<FormatConfig> type.

In Startup.cs,

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<List<FormatConfig>>(Configuration.GetSection("Formats"));

    ...
}
public class FormatConfig
{
    public string Name { get; set; }
}

Step 3

In YourController.cs, get the configuration dependency, IOptions<List<FormatConfig>> via constructor injection as below:

public class YourController : ControllerBase
{
    private readonly IOptions<List<FormatConfig>> _formatConfigOption;

    public YourController(/* Other dependencies */
        IOptions<List<FormatConfig>> formatConfigOption)
    {
        ...
        _formatConfigOption = formatConfigOption;
    }

    [HttpGet("GetFormatConfig")]
    public List<FormatConfig> GetFormatConfig()
    {
        return _formatConfigOption.Value;
    }
}

Demo

enter image description here


Reference

JSON configuration provider - Configuration in ASP.NET Core

  • Related