Read Configuration Files (.json) In .NET Core Application - Day Four

In the previous article of this series, we discussed how we can access the static files like html files using .Net Core Application. Now, in this article, we will discuss how to handle the configuration files, like json files, using Asp.Net Core application.

If you want to look at the previous articles of this series, please visit the links given below.

In the previous article, I already discussed how to access static html files using .Net Core Application. Now in this file, I will discuss how to access any configuration file during startup of the application. For these types of configuration files, we basically use .json file as a configuration file which contains different messages which will be displayed in the application.

Now, before starting the program, we will first open the Visual Studio 2017 and create a new Project with Project Type called ASP.NET Core Web Application (.Net Core) and type the project name and click on Ok Button. Then Select Empty Project type and click on OK button.

 

Now, a sample blank application project has been added. Now we need to go Nuget Package Manager for installing related packages for this configuration work under Tools à Nuget Package Manager à Manage Nuget Package Manager for Solution. Now in the nuget package manager, type the below mentioned Package manager name and click on Ok.

Now open the Solution Explorer and Properties Folder and open the launchSetting.json file. Now while seeing this file, the first question that arrises in our mind  is, "What are these files and what is the purpose of these files?"

What is launchsetting.json?

lauchSetting.json file basically contains all the project specific settings associated with each debug profile in which Visual Studio is configured for launching the application. It also includes any environment variables that should be used. We can define framework for our project for compilation and debugging for specific profiles. This file is placed in Properties folder.

 

Environment Variables

If I take the reference from Wikipedia, then it says “Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer. They are part of the environment in which a process runs.” So similarly, there are different types of environment variables present in ASP.NET 5 which can be set that will affect various parts of the runtime. But in this article, I am only interested about ASPNET_ENV variable. This variable actually defines the environment the application is currently running in. There are 3 types of values that are used by convention: Development, Staging, and Production. We are also allowed to set any value which we want.

Visual Studio Project Debug Profiles

Visual Studio 2017 supports multiple debug profiles, associated with IIS express and commands defined in project.json.

ASP.NET 5 ships with support for 3 different servers,

  • Microsoft.AspNet.Server.IIS
  • Microsoft.AspNet.Server.WebListener (WebListener)
  • Microsoft.AspNet.Server.Kestrel (Kestrel)

And the default web host for ASP.NET application created using Visual Studio 2017 is IIS/IIS express. Therefore, even for empty websites, “Microsoft.AspNet.Server.IIS” dependency is defined in project.json. And in the case of web site, there can be three different profiles. You can manage settings for each profile in debug tab of project property menu. For accessing those profiles, just open the properties window of the project files.


As per the screenshot, you can also define environment variables, launch URL, specific runtimes to use for each profile. We also need to remember the value for ASPNET_ENV (or Hosting:Environment) is case insensitive. But when you try to define the same key again for a different value, you will get a duplicate key error.

So when you modify the default settings for your project, changes are persisted in launchSettings.json. Now let’s take a look at launchsetting.json code.
  1. {  
  2.   "iisSettings": {  
  3.     "windowsAuthentication"false,  
  4.     "anonymousAuthentication"true,  
  5.     "iisExpress": {  
  6.       "applicationUrl""http://localhost:23637/",  
  7.       "sslPort": 0  
  8.     }  
  9.   },  
  10.   "profiles": {  
  11.     "IIS Express": {  
  12.       "commandName""IISExpress",  
  13.       "launchBrowser"true,  
  14.       "environmentVariables": {  
  15.         "ASPNETCORE_ENVIRONMENT""Development"  
  16.       }  
  17.     },  
  18.     "Prog_JsonFiles": {  
  19.       "commandName""Project",  
  20.       "launchBrowser"true,  
  21.       "environmentVariables": {  
  22.         "ASPNETCORE_ENVIRONMENT""Development"  
  23.       },  
  24.       "applicationUrl""http://localhost:23638"  
  25.     }  
  26.   }  
  27. }  

The first part of the file defines the IIS settings, as IIS is the default web host choice. And there are three profiles “IIS Express”, “web” and “kestrel” in the profile section. And for each profile, environment variable, runtime version to use and its command name is also defined. As mentioned earlier, command names are defined in project.json files. So when you launch your application using any of the options, the setting defined in launchsetting will be used for your web application.

Startup Conventions

I already mentioned earlier that ASPNET_ENV can have 3 value conventions: Development, Staging, and Production. And with ASP.NET 5, the Startup class is used for starting or bootstraping the application and loading all our configurations. And a convention also exists for Startup.cs and ASPNET_ENV values. You are allowed to create Startup class with environment variable name Startup{EnvironmentName} (for example StartupProduction). So I can use any one of the following: StartupDevelopment, StartupStaging and StartupProduction. And based on the ASPNET_ENV environment variable value, that Startup class is used. Thus, it gives you the flexibility to configure Startup settings for different environment.

Development

This should be the environment used when developing an application.

Staging

Actually, by most conceptions, Staging is the mid-stage environment between Development and Production. In other words, we can say that Staging Environment is the pre-production environment which is basically used for final testing before deployment of the application to the production environment. Ideally, its physical characteristics should mirror that of production, so that any issues that may arise in production occur first in the staging environment, where they can be addressed without impact to users.

Production

The Production environment is the environment in which the application runs when it is live or deployed in the client server and being used by end users. This environment should be configured to maximize security, performance, and application robustness. Some common settings that a production environment might have that would differ from development include:

  • Turn on caching
  • Ensure all client-side resources are bundled, minified, and potentially served from a CDN
  • Turn off diagnostic ErrorPages
  • Turn on friendly error pages
  • Enable production logging and monitoring (for example, Application Insights)

Now, it’s time to create our configuration object in the startup.cs file.

  1. public IConfigurationRoot Configuration { get; set; }

Above code indicates that our configuration system totally exists within the IConfigurationRoot interface.

Configuration in ASP.NET Core

The configuration API provides a way of configuring an app based on a list of name-value pairs that can be read at runtime from multiple sources. The name-value pairs can be grouped into a multi-level hierarchy. There are configuration providers for:

  • File formats (INI, JSON, and XML)
  • Command-line arguments
  • Environment variables
  • In-memory .NET objects
  • An encrypted user store
  • Azure Key Vault
  • Custom providers, which you install or create
Each configuration value maps to a string key.

IHostingEnvironment

This interface provides information about the web hosting environment of the application which is currently running. It comtains the below mentioned properties,

ApplicationName

Gets or sets the name of the application. This property is automatically set by the host to the assembly containing the application entry point.

Learn how to solve a Rubik's Cube with the easiest method, using only six algorithms.

ContentRootFileProvider

Gets or sets an IFileProvider pointing at ContentRootPath.

ContentRootPath

Gets or sets the absolute path to the directory that contains the application content files.

EnvironmentName

Gets or sets the name of the environment. This property is automatically set by the host to the value of the "ASPNETCORE_ENVIRONMENT" environment variable.

WebRootFileProvider

Gets or sets an IFileProvider pointing at WebRootPath.

WebRootPath

Gets or sets the absolute path to the directory that contains the web-servable application content files.

Now write down the below code in the program.cs file
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Hosting;  
  7.   
  8. namespace Prog_JsonFiles  
  9. {  
  10.     public class Program  
  11.     {  
  12.         public static void Main(string[] args)  
  13.         {  
  14.             var host = new WebHostBuilder()  
  15.                 .UseKestrel()  
  16.                 .UseContentRoot(Directory.GetCurrentDirectory())  
  17.                 .UseIISIntegration()  
  18.                 .UseStartup<Startup>()  
  19.                 .UseApplicationInsights()  
  20.                 .Build();  
  21.   
  22.             host.Run();  
  23.         }  
  24.     }  
  25. }  
Now write down the below code in the startup.cs file 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.Extensions.DependencyInjection;  
  9. using Microsoft.Extensions.Logging;  
  10. using Microsoft.Extensions.Configuration.Json;  
  11. using Microsoft.Extensions.Configuration;  
  12.   
  13. namespace Prog_JsonFiles  
  14. {  
  15.     public class Startup  
  16.     {  
  17.         public IConfigurationRoot Configuration { getset; }  
  18.   
  19.         public Startup(IHostingEnvironment env)  
  20.         {  
  21.             Configuration = new ConfigurationBuilder()  
  22.                             .SetBasePath(env.ContentRootPath)  
  23.                             .AddJsonFile("appSetting.json")  
  24.                             .Build();  
  25.         }  
  26.   
  27.         // This method gets called by the runtime. Use this method to add services to the container.  
  28.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
  29.         public void ConfigureServices(IServiceCollection services)  
  30.         {  
  31.         }  
  32.   
  33.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  34.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  35.         {  
  36.             loggerFactory.AddConsole();  
  37.   
  38.             if (env.IsDevelopment())  
  39.             {  
  40.                 app.UseDeveloperExceptionPage();  
  41.             }  
  42.   
  43.             app.Run(async (context) =>  
  44.             {  
  45.                 await context.Response.WriteAsync($"Hello {env.EnvironmentName} It's from {Configuration["info"]}");  
  46.             });  
  47.         }  
  48.     }  
  49. }  
Now add a json file named appSetting.json in the same location of startup.cs file and add the below code,
  1. {  
  2.   "info""Message from Configuration Files"  
  3. }  
Now run the application and output as below,


You can read the next part here,