ASP.NET Core - Configuration


Advertisements

In this chapter, we will be discussing the configuration related to ASP.NET Core project. In Solution Explorer, you will see the Startup.cs file. If you have worked with previous versions of ASP.NET Core, you will probably expect to see a global.asax file, which was one place where you could write codes to execute during startup of a web application.

  • You would also expect to see a web.config file containing all the configuration parameters your application needed to execute.

  • In ASP.NET Core those files are all gone, and instead of configuration and startup code are loaded from Startup.cs.

  • There is a Startup class inside the file and in this class you can configure your application and even configure your configuration sources.

Here is the default implementation in the Startup.cs file.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 

using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Hosting; 
using Microsoft.AspNetCore.Http; 

using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Logging;  

namespace FirstAppDemo { 
   public class Startup { 
      // This method gets called by the runtime.
      // Use this method to add services to the container. 
      // For more information on how to configure your application, 
      // visit http://go.microsoft.com/fwlink/?LinkID=398940 
      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) => { 
            await context.Response.WriteAsync("Hello World!"); 
         }); 
      } 
   } 
}

In the Startup class, there are two methods where most of our work will take place. The Configure method of the class is where you build your HTTP processing pipeline.

  • This defines how your application responds to requests. Currently this application can only say Hello World! and if we want the application to behave differently, we will need to change the pipeline around by adding additional code in this Configure method.

  • For example, if we want to serve the static files such as an index.html file, we will need to add some code to the Configure method.

  • You can also have an error page or route requests to an ASP.NET MVC controller; both of these scenarios will also require to do some work in this Configure method.

  • In the Startup class, you will also see the ConfigureServices() method. This helps you configure components for your application.

Right now, we have a hard-coded string for every response — the Hello World! string. Instead of hard-coding the string, we want to load this string from some component that knows the text that we want to display.

  • This other component might load that text from a database or a web service or a JSON file, it doesn't matter where exactly it is.

  • We will just set up a scenario so that we do not have this hard-coded string.

In the Solution Explorer, right-click on your project node and select Add → New Item.

Add First Item

In the left pane, select Installed → Code and then in the middle pane, select the JSON File. Call this file AppSettings.json and click on the Add button as in the above screenshot.

Installed Code

We can also have our program read the text from the file instead of having the Hello World! String in Startup.cs. Let us add the following code in AppSettings.json file.

{ 
   "message": "Hello, World! this message is from configuration file..." 
}

Now we need to access this message from the Startup.cs file. Here is the implementation of the Startup.cs file which will read the above message from the JSON file.

using Microsoft.AspNet.Builder; 
using Microsoft.AspNet.Hosting; 
using Microsoft.AspNet.Http; 

using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Configuration;  

namespace FirstAppDemo { 
   public class Startup { 
      public Startup() { 
         var builder = new ConfigurationBuilder()   
            .AddJsonFile("AppSettings.json"); 
         Configuration = builder.Build(); 
      }  
      public IConfiguration Configuration { get; set; }  
      
      // This method gets called by the runtime. 
      // Use this method to add services to the container. 
      // For more information on how to configure your application, 
      // visit http://go.microsoft.com/fwlink/?LinkID=398940 
      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) {
         app.UseIISPlatformHandler();  
         app.Run(async (context) => { 
            var msg = Configuration["message"]; 
            await context.Response.WriteAsync(msg); 
         });  
      }  
        
      // Entry point for the application. 
      public static void Main(string[] args) =7gt; WebApplication.Run<Startup>(args); 
   } 
}

Let us now run the application. Once you run the application, it will produce the following output.

Run The Application
Advertisements