ASP. NET Core 2.0: five. How the service is loaded and run, Kestrel, configuration and environment

Source: Internet
Author: User
Tags webhost

How does the "Cross-platform" of ASP. NET core receive and process requests? What is the difference between its operating and processing mechanisms?

This chapter looks at its structure and what has been done in different periods from "macro" to "microscopic".

The main contents of this chapter are as follows:

The operating mechanism of ASP: "Macro" to look at the HTTP request processing process.

Configuration and operation of asp: twice times the magnified ASP. Application, Kestrel Server, startup and configuration

environment variables for ASP.

Operating mechanism of ASP. NET Core

Figure 1

The operating mechanism for ASP. NET Core is as shown in the detailed description now.

①web Server: ASP. NET core is available in two types of servers, Kestrel and HTTP. SYS (named Weblistener in Core 1.x).

A. Kestrel is a cross-platform Web server;

B. http. SYS can only be used on Windows systems.

②internet: you can choose HTTP. sys when you need to deploy in internal Network and require features that are not in Kestrel, such as Windows authentication.

③iis, Apache, Nginx: Kestrel can be used alone or in conjunction with a reverse proxy server such as IIS, Nginx, or Apache. Requests are processed for initial processing by these servers and forwarded to Kestrel (the optional flow of dashed lines in the figure).

The approximate operating mechanism is this, so how does the ASP. NET core application work? We'll zoom in on the red box of ASP. NET core application in Figure 1 to see the next section.

ASP. NET Core Startup

Take a look at the magnified image of the ASP. NET Core application in Figure 1:

Figure 2

④main method, the starting point of the program.

⑤ Create and configure Webhostbuilder: First call Createdefaultbuilder (which is a large set of configurations, described in detail below), after a series of configurations, call usestartup<t> (),

Specifies that the ⑩startup is the startup configuration file. In startup, there will be two more important jobs, ⑧ the Dependency injection and ⑨ configuration pipeline for the service, which will be described in detail later in this section.

After ⑥ generated the Webhostbuilder and made a series of configurations, this webhostbuilder builds a iwebhost.

⑦ calls Iwebhost's Run method to get it to run.

An ASP. NET Core application is essentially a console application, so it is also a starting point for the program with a familiar main method.

Open the Program.cs file, the default is the following code

public class program{public    static void Main (string[] args)    {        buildwebhost (args). Run ();    }    public static Iwebhost Buildwebhost (string[] args) =        webhost.createdefaultbuilder (args)            . Usestartup<startup>()            . Build ();}   

Defines a buildwebhost method, which is called in Main to return a iwebhost, and makes the Iwebhost "run up." Then look inside the Buildwebhost method, by calling Createdefaultbuilder

Create a iwebhostbuilder, then use this builder to build a iwebhost.

In simple terms, create iwebhostbuilder=>builder=>build () =>iwebhost=>run ().

A series of configurations for Webhostbuilder

System can not be separated from a variety of configurations, such as the common read configuration files, specify the log processing program, we look at a detailed.

Createdefaultbuilder

Createdefaultbuilder, as the name implies, is a default configuration. 2, it is mainly called a variety of configurexxx and usexxx, first look at its source code

1  Public StaticIwebhostbuilder Createdefaultbuilder (string[] args)2 {3     varBuilder =NewWebhostbuilder ()4         . Usekestrel ()5         . Usecontentroot (Directory.GetCurrentDirectory ())6. Configureappconfiguration ((hostingcontext, config) =7         {8             varenv =hostingcontext.hostingenvironment;9 TenConfig. Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true) One. Addjsonfile ($"appsettings. {env. Environmentname}.json", Optional:true, Reloadonchange:true); A  -             if(env. Isdevelopment ()) -             { the                 varappassembly = Assembly.Load (NewAssemblyName (env. ApplicationName)); -                 if(appassembly! =NULL) -                 { -Config. Addusersecrets (appassembly, Optional:true); +                 } -             } +  A CONFIG. Addenvironmentvariables (); at  -             if(Args! =NULL) -             { - CONFIG. Addcommandline (args); -             } -         }) in. Configurelogging (hostingcontext, logging) = -         { toLogging. Addconfiguration (HostingContext.Configuration.GetSection ("Logging")); + logging. Addconsole (); - logging. Adddebug (); the         }) *         . Useiisintegration () $. Usedefaultserviceprovider (context, options) =Panax Notoginseng         { -Options. Validatescopes =context. Hostingenvironment.isdevelopment (); the         }); +  A     returnBuilder; the}

The above source code we see it these configurexxx and usexxx process, and in the core 1.0 version is not createdefaultbuilder this method,

The system calls these configurexxx and usexxx by default, and in Core 2.0, for the simplicity and ease of use of the code, put the methods that need to be called in the general case into the method named Createdefaultbuilder.

In general, calling Createdefaultbuilder to perform these default configurations is sufficient. But since this is the default configuration, we can customize it according to our own circumstances.

Because these configurations are modified Webhostbuilder, and then return the modified Webhostbuilder again after modification, you can customize the following methods if the Createdefaultbuilder does not meet the actual requirements.

1) do not call Createdefaultbuilder, the above mentioned configuration selective execution, even can add, replace some of the configuration inside, such as the Usekestrel to Usehttpsys.

2) Minor changes, that is, call Createdefaultbuilder and then return the Webhostbuilder to the custom other configuration method. For example, you can call Configureappconfiguration again to add more configuration sources.

Here's a look at these configurexxx and usexxx.

A. Usekestrel

Used to designate the server to use Kestrel, use Usehttpsys if you use Httpsys.

Kestrel is a cross-platform ASP. NET Core Web server based on LIBUV (a cross-platform asynchronous I/O Library). Kestrel is a WEB server that is included by default in the ASP. NET Core project template.

Kestrel supports the following features:

    • HTTPS
    • Opaque upgrade for enabling WebSocket
    • Used to obtain Nginx high-performance Unix sockets.

By default, the ASP. NET Core project template uses Kestrel.

We can call Usekestrel again to modify the configuration of the kestrel, for example, to limit the maximum value of the request body

 Public Static Iwebhost buildwebhost (string[] args) =    webhost.createdefaultbuilder (args)        . Usestartup<Startup>()        = +            ;
}) . Build ();

B. Usecontentroot

Specifies the root directory for the application. Note that this is different from the root of Staticfiles, although the root of Staticfiles is based on contentroot ([contentroot]/wwwroot) by default.

C. configureappconfiguration

Read the configuration. As the above code reads Appsettings.json and appsettings.{ Env. Environmentname}.json , Env. Environmentname refers to the environment, such as development. The user key is also read when in the development environment .

This section is described in detail when learning the system configuration.

D. configurelogging

Configure log handlers, console and debug log providers, and learn more about the logs.

E. useiisintegration

Configure the application to run in IIS. As already mentioned, Usekestrel is still needed here, and IIS acts as a reverse proxy, while Kestrel is still used as a host.

If the application does not use IIS as the reverse proxy, then useiisintegration will not have any effect. Therefore, this method can be safely called even if the application is running in a non-IIS scenario.

F.usedefaultserviceprovider

Set the default dependency injection container, which is detailed later when learning about dependency injection.

The environment of ASP.

A very important and commonly used thing in ASP. is called an environment variable, which is specified by the ASPNETCORE_ENVIRONMENT environment variable.

We can set this variable to any value as needed, but we usually use values development, Staging, and Production. It defines the operating environment of the current application, and we often use this variable to allow the application to be handled differently.

In the example above, there is such a usage

if (env. Isdevelopment ()) {     var appassembly = Assembly.Load (new  AssemblyName (env). ApplicationName));      if NULL )     {          true);}     }

In _layout View

    <environment include="development">        <link rel="stylesheet  " href="~/lib/bootstrap/dist/css/bootstrap.css "/>        <link rel="stylesheet" href="~/css/site.css" />    </environment>

Therefore, if you set the Aspnetcore_environment variable to development (or set this environment variable in the Launchsettings.json file) before run,

The application runs in development mode, not Production mode (this is the default mode when no variables are set).

Note: Environment variables and values are not case-sensitive on Windows and MacOS. Linux environment variables and values are case-sensitive.

Summary

Through the above content about ASP. NET Core 2.0 service start, configuration and operation, the operating environment, such as a general understanding, which involves some content such as reading configuration, logs, etc., will be introduced separately later.

In addition to the above, the place where ASP. NET core left us as an extension is primarily in the Startup file, the ⑩startup in Figure 2 , where two more important work is done, ⑧ the dependency injection and ⑨ configuration pipeline for the service ,

Below we will enlarge the red box of ⑩startup in Figure 2to see what has been done here.

ASP. NET Core 2.0: five. How the service is loaded and run, Kestrel, configuration and environment

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.