Friday, February 22, 2019

Adding Configuration to Asp.Net Core

Configuration is another important aspect of any Application, in this post we shall see on how to add a configuration file and read the key/value pairs from the config file in the application. In traditional Asp.Net and MVC applications we had a default web.config file where we can add the config entries and use them in the application. Asp.Net core is different, here we use a JSON file for the configurations. In this post we will add a configuration file appsettings.json and read the config entries from the file at Startup.

Let us use the basic Hello World application and modify it slightly to add the configurations. First add a new JSON file to the application, name it appsettings.json. Let us add a config entry to the file as follows.
{
  "myConfigKey":  "Hello from Config"
}

Next open the Startup.cs file and a ConfigurationBuilder to read the settings from the appsettings.json file as follows.

    public class Startup
    {
        public IConfiguration Configuration { get; set; }
        public Startup()
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            Configuration = builder.Build();
        }
        public void ConfigureServices(IServiceCollection services)
        {
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseDeveloperExceptionPage();

            app.Run(async (context) =>
            {
                var configValue = Configuration["myConfigKey"];
                await context.Response.WriteAsync(configValue);
            });
        }
    }

Build and run the application, notice that it displays the value "Hello from Config"  from the config file in the browser.


Search Flipkart Products:
Flipkart.com

No comments: