Dot Net For All

How to add ASP.NET Core Web configuration file

This article will help you to understand about adding the ASP.NET Core Web Configuration File. In my previous article I have discussed about the prerequisites to develop ASP.NET core web project and the asp.net core web project structure. The links are below.

Adding an ASP.NET Core Web Configuration File

Please check the code for the Startup.cs in below figure.

  public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var confBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appsettings.json");
            Configuraion = confBuilder.Build();
        }

        public IConfiguration Configuraion { get; set; }

        
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                var messsage = Configuraion["HelloWorld"];
                await context.Response.WriteAsync(message);
            });
        }
    }

Once we change the Startup.cs constructor and add the code as shown in the snippet above, I have to add new nuget references by pressing the “ctrl + .(dot)” on the error code as shown in the below figure.

and we can see that one more dependency is added to the project.json as  “Microsoft.Extensions.Configuration.Json”: “1.0.0”

Now as we have the setup ready to read the configuration file. We can see in the above code that we are reading the “HelloWorld” message in the Configure method and writing it on the response.

Once we run the project we will see the message “Hello World from Configuration” in the browser.

Conclusion

We have added the ASP.NET Core Web Configuration File to the exiting project. And see how it is  different from the web.config file we have used till now in our web development.

Master you .NET Core concepts

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview