Thursday, April 9, 2020

Access configuration settings from custom configuration files

In the previous post we saw on how to read configuration settings from the appsettings.json file. While this holds good for most of the cases, there might be situations where we will need our custom configuration file, when we use our own configuration file, we need to specify the file in the Startup and add the file to the ConfigurationBuilder.

In the below case we have a custom configuration file mysettings.json, and we will read the configuration settings from our config file.

public class Startup
{
    public IConfiguration Configuration { get; set; }
    public Startup()
    {
        var builder = new ConfigurationBuilder().AddJsonFile("mysettings.json");
        this.Configuration = builder.Build();
    }
    public void ConfigureServices(IServiceCollection services)
    {
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseDeveloperExceptionPage();
        app.UseStaticFiles();

        app.Run(async (context) =>
        {
            var myValue = Configuration["myConfigKey"];
            var connectionString = Configuration["ConnectionStrings:myConnectionString"];
            Console.WriteLine("My Config Value: " + myValue);
            Console.WriteLine("Connection String: " + connectionString);
            await context.Response.WriteAsync("Hello World");
        });
    }
}

Build and run the sample, the output will be similar to the previous post, except that we are using a custom config file instead of appsettings.json.


Search Flipkart Products:
Flipkart.com

No comments: