ASP. NET Core 2.0: 5. How to load and run services, Kestrel, configuration and environment, corekestrel
How does the ASP. Net Core after "cross-platform" Receive and process requests? What is the difference between its running and processing mechanism and the previous one?
This chapter looks at its structure and what has been done in different periods from "macro" to "micro.
The main content of this chapter is as follows:
ASP. NET Core operating mechanism: "macro" to see the Http request processing process.
Configuration and running of ASP. NET Core: ASP. NET Core Application, Kestrel server, startup and configuration after 2x magnification
Environment Variable of ASP. NET Core.
Operating Mechanism of ASP. NET Core
① Web Server: ASP. NET Core provides two types of servers available: 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 in Windows.
② Internet: You can select HTTP. sys when you need to deploy it in the Internal Network and do not need features in Kestrel (such as Windows Authentication.
③ IIS, Apache, and Nginx: Kestrel can be used independently or in combination with reverse proxy servers (such as IIS, Nginx, or Apache. Requests are forwarded to Kestrel after preliminary processing by these servers (that is, the optional process of the dotted line in the figure ).
This is probably the operating mechanism. How does ASP. NET Core Application run? We will enlarge the red box ASP. NET Core Application in figure 1 to see the next section.
ASP. NET Core startup
Let's see how ASP. NET Core Application in Figure 1 is enlarged:
UseStartup <T> (),
Specify Startup as the Startup configuration file. In Startup, two important tasks will be performed, the dependency injection and pipeline configuration pipeline of the Startup service. This section will be described in detail later.
6. After the WebHostBuilder is generated and a series of configurations are performed, the WebHostBuilder is used to Build an IWebHost.
7. Call the Run method of IWebHost to start running.
ASP. NET Core applications are essentially console applications, so they use a familiar Main method as the starting point of the program.
Open the Program. cs file. The default code is as follows:
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, calls it in Main to return an IWebHost, and makes the IWebHost "Run". Then, inside the BuildWebHost method, call createdefabuilder Builder
Create an IWebHostBuilder and use this Builder to Build an IWebHost.
To put it simply, create IWebHostBuilder => Builder => Build () => IWebHost => Run ().
A series of WebHostBuilder configurations
The system is inseparable from various configurations, such as reading configuration files and specifying log processing programs. Let's take a look at them in detail.
Create ultbuilder
Createdefabuilder builder, as its name implies, is a default configuration. 2 shows that it mainly calls various ConfigureXXX and UseXXX. First, let's take a look at its source code.
1 public static IWebHostBuilder CreateDefaultBuilder(string[] args) 2 { 3 var builder = new WebHostBuilder() 4 .UseKestrel() 5 .UseContentRoot(Directory.GetCurrentDirectory()) 6 .ConfigureAppConfiguration((hostingContext, config) => 7 { 8 var env = hostingContext.HostingEnvironment; 9 10 config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)11 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);12 13 if (env.IsDevelopment())14 {15 var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));16 if (appAssembly != null)17 {18 config.AddUserSecrets(appAssembly, optional: true);19 }20 }21 22 config.AddEnvironmentVariables();23 24 if (args != null)25 {26 config.AddCommandLine(args);27 }28 })29 .ConfigureLogging((hostingContext, logging) =>30 {31 logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));32 logging.AddConsole();33 logging.AddDebug();34 })35 .UseIISIntegration()36 .UseDefaultServiceProvider((context, options) =>37 {38 options.ValidateScopes = context.HostingEnvironment.IsDevelopment();39 });40 41 return builder;42 }
In the source code above, we can see the ConfigureXXX and UseXXX processes. In Core 1.0, the createdefabuilder builder method is not available,
The ConfigureXXX and UseXXX are called one by default. In Core 2.0, for the sake of concise code and convenient use, put the methods that need to be called in these general cases to the createdefabuilder builder method.
Generally, it is enough to call Create defadefabuilder to execute these default configurations. However, since this is the default configuration, We can customize it based on our own situation.
Because these configurations are modified by WebHostBuilder, and the modified WebHostBuilder is returned again, the following method can be used to customize the WebHostBuilder if the "Create ultbuilder" does not meet the actual needs.
1) if you do not call the Create defabuilder builder, You can selectively execute the configurations mentioned above, or even add or replace some configurations, such as changing UseKestrel to UseHttpSys.
2) slightly changed, that is, call Create defabuilder and then call other custom configuration methods for the returned WebHostBuilder. For example, you can call ConfigureAppConfiguration again to add more configuration sources.
The following describes ConfigureXXX and UseXXX.
A. UseKestrel
It is used to specify that the server uses Kestrel. If HttpSys is used, UseHttpSys is used.
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, which is included in the ASP. NET Core Project template by default.
Kestrel supports the following features:
- HTTPS
- Used to enable the opaque upgrade of WebSocket
- This interface is 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 Kestrel configuration, for example, limit the maximum value of the Request body.
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseKestrel(options => { options.Limits.MaxRequestBodySize = 10 * 1024;
}) .Build();
B. UseContentRoot
Specify the root directory for the application. Note that this is different from the root of StaticFiles, although by default, the root of StaticFiles is based on ContentRoot ([ContentRoot]/wwwroot ).
C. ConfigureAppConfiguration
Read configurations. The above Code reads the deleettings. json and appsettings. {env. environmentName }. json, env. environmentName refers to the environment, for example, Development. in the Development environment, the User Key is also read.
This section describes system configuration in detail.
D. ConfigureLogging
Configure the log handler, console, and debug the log provider. Learn more about the log.
E. UseIISIntegration
Configure the application to run in IIS. As mentioned above, UseKestrel is still needed here, while 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, UseIISIntegration will not have any effect. Therefore, this method can be safely called even if the application runs in a non-IIS solution.
F. usedefaserviceserviceprovider
Set the default dependency injection container, which will be detailed later when learning dependency injection.
ASP. NET Core Environment
In ASP. NET Core, an important and common thing is the environment variable, which is specified by the ASPNETCORE_ENVIRONMENT environment variable.
We can set this variable to any value as needed, but the value Development, Staging, and Production are usually used. It defines the runtime environment of the current application. We often use different processing methods based on this variable.
In the above example, this is an example.
if (env.IsDevelopment()){ var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); }}
_ 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 before run (or set this environmental variable in the launchSettings. json file ),
The application runs in the Development mode instead of the Production mode (this is the default mode when no variables are set ).
Note: On Windows and macOS, environment variables and values are case-insensitive. Linux environment variables and values are case sensitive.
Summary
According to the above content. NET Core 2.0 has a rough understanding of the Service Startup, configuration and running, and runtime environment. Some of the content involved, such as reading configuration and logs, will be separately introduced later.
In addition to the above content, ASP. NET Core is left to us as the extension in the Startup file, that is, commit Startup in Figure 2. Two important tasks are carried out here, the dependency injection and pipeline configuration pipeline of the ingress service,
In the following section, we will zoom in the margin Startup box in Figure 2 to see what has been done here.