Analysis of ASP.NET Core Operating Principle

Analysis of ASP.NET Core Operating Principle

Plan 

1. ASP.NET Core operating principle analysis

1.1. Overview

1.2. File configuration

1.2.1. Startup file configuration

  • Configure
  • ConfigureServices

1.2.2. Appsetting.json configuration

1.3. Handling Pipes (Middleware)

1.4 Summary

1. ASP.NET Core operating principle analysis

1.1. Overview

Prior to ASP.NET Core, the ASP.NET Framework application was loaded by IIS. The entry point for the Web application is created by InetMgr.exe and called for hosting. Initiate the HttpApplication.Application_Start () event during initialization. The opportunity for the developer to execute the code for the first time is to handle the events in Application_StartGlobal.asax. In ASP.NET Core, the Global.asax file is no longer available and has been replaced by a new initialization process.


The ASP.NET Core application invokes a specific library under the .NET Core console program, which is a fundamental change in ASP.NET Core application development. All ASP.NET managed libraries are executed from the program, not hosted by IIS. That is, the .NET Tool-Chain can be used for both the .NET Core console application and the ASP.NET Core application.

using System;
        using Microsoft.AspNetCore.Hosting;

        namespace aspnetcoreapp
        {
        public class Program
        {
            public static void Main(string[] args)
            {

                var host = new WebHostBuilder()
                    .UseKestrel() // specify the host program as Kestrel
                    .UseStartup<Startup>()// Call the Configure and ConfigureServices under the Startup.cs class
                    .Build();

                host.Run();
             }
        }
    }

The above is the example code of the Main method in the Program class. The Main method is responsible for initializing the Web host, calling Startup, and executing the application. The host will call the Configure and ConfigureServices methods under the Startup class.

1.2. File configuration

1.2.1. Startup file configuration

For an ASP.NET Core program, the Startup class is required. ASP.NET Core will start from the Program class when the program starts, and then find the UseStartup <Startup> find the configuration of the Startup class if not specified Startup class will lead to failure to start. Must be defined in the Startup Configure method, and ConfigureServices method is optional, the method will be called the first time the program is called, similar to the traditional ASP.NET MVC routing and application status can be configured in the Startup, also You can initialize the required middleware here.

Configure

In the ASP.NET Core application, the Configure method is used to specify how the middleware responds to HTTP requests.

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

namespace aspnetcoreapp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
                        
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            
            app.UseStaticFiles();
                                    
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

ASP.NET Core is through the IApplicationBuilder expansion to build middleware, the above code in each use extension method is to add middleware to the request pipeline. You can also add services to the Configure method (eg, IHostingEnvironment) These services are initialized in the ConfigureServices method.

With the ASP.NET Core project template to add the application, the default to add a few middleware:

UseStaticFiles allows an application to provide static resources.

UseMvc adds MVC to the pipe and allows routing.

ConfigureServices

The ConfigureServices method adds the MVC service to the container by default when the application is running to add the service to the container, using the ASP.NET Core project template by default:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

Next, in an example, the ConfigureServices method is used in conjunction with the Configure method. There is a UI development framework in ASP.NET Core that has more than 60 UI components, not just ASP.NET Core cross-platform deployment model, but also supports front-end adaptive rendering.

When the Telerik UI is applied to the project, the related packages are first referenced in the project, and then the Kendo UI service is added to the container in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddKendo();
}

Next, set up the Kendo UI in Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    app.UseKendo(env);
}

1.2.2. Appsetting.json configuration

The Configuration API provides a way to configure an application based on a key-value pair that can be read from multiple sources at run time. Key-value pairs can be grouped to form a multilayer structure. Key-value pairs can be configured in different places, such as: files, memory, etc., which can not be stored in memory, where I choose to configure it in the appsetting.json file inside.

Configure the appsetting file

{
  "key1": 1,
  "key2": 2,
  "key3":true,

  "parentObj": {
    "key1": "sub-key1"
  },
  "members": [
    {
      "name": "Lily",
      "age": "18"
    },
    {
      "name": "Lucy",
      "age": "17"
    }
  ]

A hierarchical structure of the JSON file, the key (eg key1) as an indexer, the value as a parameter, the type can be a string, a number, a boolean, an object or an array. The following specific look at how to use in the application.

In the application to load and apply the configuration file.

public static IConfigurationRoot Configuration { get; set; }

public static void Main(string[] args = null)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");

    Configuration = builder.Build();

    Console.WriteLine($"key1 = {Configuration["key1"]}");
    Console.WriteLine($"key2 = {Configuration["key2"]}");
    Console.WriteLine(
        $"subkey1 = {Configuration["parentObj:key1"]}");
    Console.WriteLine();

    Console.WriteLine("members:");
    Console.Write($"{Configuration["members:0:name"]}, ");
    Console.WriteLine($"age {Configuration["members:0:age"]}");
    Console.Write($"{Configuration["members:1:name"]}, ");
    Console.WriteLine($"age {Configuration["members:1:age"]}");
    Console.WriteLine();

    Console.WriteLine("Press a key...");
    Console.ReadKey();
}

As a result of loading a JSON file, so the file loaded into the program can be directly after it as a JSON object to use. If you have a dynamic language experience with the students this way is more familiar with the way. Only when you visit the property here will usually be common. Into: This and write JSON object closer.

1.3. Handling Pipes (Middleware)

Using middleware in an ASP.NET Core application, anything that the application does (including static files in the server) is done by middleware. An application that does not have any middleware simply returns 404 Not Found at the time of the request error. Middleware allows you to completely control the handling of requests and make your application more streamlined.

When a request is received, the request is processed by the middleware pipeline consisting of the middleware. The pipeline is composed of multiple middlewares. The request comes from one end of a middleware and comes from the other end of the middleware. Each middleware You can handle the start and end of the HttpContext request.

In ASP.NET Core, you can use Run, Map and Use in three ways to configure HTTP pipes. The Run method is called a short-haul pipeline (because it does not call next to request a delegate). Thus, the Run method is typically called at the end of the pipe. Run is a convention, some middleware components may expose their own Run methods, and these methods can only run at the end of the pipeline. The following two codes are equivalent because Use does not call the next method.

Run method sample code

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

    app.Run(async context =>
        {
            await context.Response.WriteAsync("environment " + env);
        });

}

The Use method does not execute the sample code for next

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

    app.Use(async (context, next) =>
        {
            await context.Response.WriteAsync("environment " + env);
        });

}

In .NET Core, the Map * extension is used to branch the pipeline, and the current implementation has supported the request path or the predicate to enter the branch. The Map extension method is used to match request requests based on the request path. Map only accepts paths and configures the functionality of separate middleware pipes.

private static void HandleMapUrl(IApplicationBuilder app)
{
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Map Url Test Successful");
    });
}
public void ConfigureMapping(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Map("/mapurl", HandleMapUrl);
}

In the example above, the Map method is used to accept the path into the branch pipe, that is, all the / mapurl path requests are handled by the HandleMapUrl method in the pipeline; if you want to use the predicate to enter the middleware branch, use the MapThen method. The MapThen method allows a very flexible way to build an intermediate pipe. For example, you can check whether the query string has 'branch' to enter the branch:

private static void HandleBranch(IApplicationBuilder app)
{
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Branch used.");
    });
}
public void Configure(IApplicationBuilder app)
{
    app.MapWhen(context => {
        return context.Request.Query.ContainsKey("branch");
    }, HandleBranch);

}

1.4 Summary

This section explains how the ASP.NET Core first loads the Main method below the Program class at runtime, specifies the managed server in the Main method and calls the Configure and ConfigureServices methods in the Startup class to complete the initialization;

In ASP.NET Core HTTP requests are processed in the form of middleware pipes, each middleware can be in the HTTP request to start and end of processing to deal with it;

ASP.NET Core can build cross-platform applications, the service runs on Http.Sys (Windows platform only) and Kestrel, do not need to use IIS hosting, so compared to traditional ASP.NET performance is more efficient and more flexible.

要查看或添加评论,请登录

Hamida Rebai Trabelsi的更多文章

社区洞察

其他会员也浏览了