English 中文(简体)
ASP.NET Core - Configuration
  • 时间:2024-11-03

ASP.NET Core - Configuration


Previous Page Next Page  

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 apppcation.

    You would also expect to see a web.config file containing all the configuration parameters your apppcation 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 apppcation 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 { 
   pubpc 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 apppcation, 
      // visit http://go.microsoft.com/fwpnk/?LinkID=398940 
      pubpc void ConfigureServices(IServiceCollection services) { 
      }  
      
      // This method gets called by the runtime. Use this method to configure 
      // the HTTP request pipepne.
      pubpc void Configure(IApppcationBuilder 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 pipepne.

    This defines how your apppcation responds to requests. Currently this apppcation can only say Hello World! and if we want the apppcation to behave differently, we will need to change the pipepne 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 apppcation.

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-cpck 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 cpck 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 { 
   pubpc class Startup { 
      pubpc Startup() { 
         var builder = new ConfigurationBuilder()   
            .AddJsonFile("AppSettings.json"); 
         Configuration = builder.Build(); 
      }  
      pubpc 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 apppcation, 
      // visit http://go.microsoft.com/fwpnk/?LinkID=398940 
      pubpc void ConfigureServices(IServiceCollection services) { 
      }  
      
      // This method gets called by the runtime.  
      // Use this method to configure the HTTP request pipepne. 
      pubpc void Configure(IApppcationBuilder app) {
         app.UseIISPlatformHandler();  
         app.Run(async (context) => { 
            var msg = Configuration["message"]; 
            await context.Response.WriteAsync(msg); 
         });  
      }  
        
      // Entry point for the apppcation. 
      pubpc static void Main(string[] args) =7gt; WebApppcation.Run<Startup>(args); 
   } 
}

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

Run The Apppcation Advertisements