Thursday, April 9, 2020

Access configuration settings from appsetting.json

We saw about the various configuration options provided by .Net Core in the previous post. In this post we shall see on how to use the configuration file option to store and retrieve key-value configuration settings.

Traditionally we are used to store configuration settings in environmental variables or config files like .INI files, web.config files etc. Asp.Net core provides a default JSON based configuration file called appsettings.json file. In this post we shall see on how to read configuration settings from the appsettings.json file in the application startup.
 Reading config setting values from the default appsettings.json is very simple, in the following code we will read 2 config keys myConfigKey & myConnectionString and display the values in the console.

appsettings.json

{
  "myConfigKey": "Hello from Config",
  "ConnectionStrings": {
    "myConnectionString": "My Connection String"
  }
}

Notice that the key myConnectionString is nested under a parent element ConnectionStrings.
Following is the Startup class which reads the config setting in app start.

public class Startup
{
    public IConfiguration Configuration { get; set; }
    public Startup(IConfiguration configuration)
    {
        this.Configuration = configuration;
    }
    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 application and notice that the config values are displayed in the console as follows.



Search Flipkart Products:
Flipkart.com

No comments: