KestrelServer’s biggest advantage is its cross-platform capabilities, if ASP.NET CORE applications only need to be deployed in the Windows environment, IIS is also a good choice. ASP.NET CORE applications have two deployment modes for IIS, both of which rely on an IIS extension module for ASP.NET CORE Core.

一、ASP.NET CORE Core Module 二、 In-Process deployment mode three、Out-of-Process deployment mode 四、配置

IIS actually handles requests in the same way as pipelines, but IIS pipelines are fundamentally different from ASP.NET CORE middleware pipelines. For web applications deployed in IIS, the process is broken down from the initial receipt of the request to the final dispatch of the response, each with one or two (prepend+post) corresponding events or callbacks. We can take over the request at the right time with a custom Module to register the appropriate event or callback and handle it the way we want.

IIS offers a range of native modules that we can also use any. The .NET language writes a hosted module, integrating IIS and ASP.NET CORE ASP.NET CORE Core Module is a native module. It uses registered events to intercept requests from the IIS pipeline and forward them to the ASP.NET CORE pipeline for processing. The corresponding installation package can be downloaded from https://dotnet.microsoft.com/permalink/dotnetcore-current-windows-runtime-bundle-installer.

ASP.NET CORE has two deployment modes: In-Process and Out-of-Process under IIS. ASP.NET CORE applications in In-Process mode run in the IIS worker process w3wp .exe (if IIS Express is used, the worker process is iisexpress .exe). As shown in Figure 18-7, the server type used by ASP.NET CORE application in this mode is IISHttpServer, and the above ASP.NET CORE Core Module forwards the original request to this server and forwards the latter generation response to the IIS server for reply.

Figure 1 In-Process deployment mode

In-Process is the default deployment mode, so we don’t need to do any setup for this, so let’s demonstrate the specific deployment method. We create an app called WebApp at the default site of IIS (Defaut Web Site) and set the mapped physical path to “C:\App”. Then we create an empty ASP.NET CORE program and write the following demo program that uses the current process name as the content of the response.

Then we right-click on the project in Visual Studio’s solution view, select the “Publish” option in the pop-up menu, create a Publish Profile that points to “C:\App”, and execute this profile to complete the publishing work. App publishing can also be done by executing the command line “dotnet publish”. After the application is deployed, we use the browser to use the address “http://localhost/webapp” to access the deployed application, and from the output shown in Figure 2 ASP.NET CORE application is actually running in the worker process of IIS.

Figure 2 The name of the process in In-Process mode

If I look at the deployment directory (“C:\App”) at this point, I see the generated assemblies and configuration files. Since the application is deployed in IIS, the specific configuration is naturally defined in web.config, as shown in the contents of this file. We will find that all requests (path=”*” verb=”*”) are mapped to the “AspNetCoreModuleV2” module, which is the ASP.NET CORE Core Module described above. As for this Module, if it starts ASP.NET the CORE pipeline and interacts with it, it is controlled by the configuration section that follows, and you can see that it sets the hostingModel property, which represents the deployment mode, to “inprocess”.

The In-Process mode registers the following IISHttpServer, with the corresponding configuration options defined in IISServerOptions. If we have the need to synchronize the read and write request and response body content, we need to set the AllowSynchronousIO property (False by default) to True. If the AutomaticAuthentication property is returned True (the default), the authenticating user is automatically assigned to the User property of the HttpContext context. We can use the MaxRequestBodyBufferSize (default is 1,048,576) and the MaxRequestBodySize property (default is 30,000,000) to set the buffer capacity of the receive request body, and the maximum number of bytes of the request body.

The registration implementation for IISHttpServer is in the IWebHostBuilder interface in the UseIIS extension method below. Since this method does not provide an Action delegate parameter to set the IISServerOptions configuration option, we had to set it in its original form. Since the IHostBuider interface ConfigureWebHostDefaults extension method calls this method internally, we don’t need to do extra work for this.

ASP.NET CORE applications can also be deployed in IIS in the Out-of-Process mode. As shown in Figure 3, under this deployment, ASP.NET CORE applications with KestrelServer run in a separate dotnet .exe process. When IIS accepts a request for the target application, if the process in which the target application is located does not start, ASP.NET CORE Core Module is also responsible for executing the dotnet command to activate the process, which is equivalent to acting as a WAS (Windows Activation Service).

Figure 3 Out-of-Process deployment mode

Before activating the ASP.NET CORE hosting process, ASP.NET CORE Core Module selects an available port number that and the path of the current application (which will act ASP.NET the PathBase of the CORE application) are written to the environment variable with the corresponding environment variable names “ASPNETCORE_PORT” and “ASPNETCORE_APPL_PATH”, respectively. ASP.NET CORE applications deployed in Out-of-Process mode will only receive requests forwarded to it by IIS, and in order to be able to filter requests from other sources, ASP.NET CORE Core Module generates a token and writes to the environment variable “ASPNETCORE_TOKEN”. Subsequent forwarded requests pass this token using a header “MS-ASPNETCORE-TOKEN”, and the ASP.NET CORE application verifies that it matches the previously generated token.

ASP.NET CORE Core Module also uses environment variables to pass other settings, with authentication schemes written to the environment variable “ASPNETCORE_IIS_HTTPAUTH” and another “ASPNETCORE_IIS_WEBSOCKETS_SUPPORTED” environment variable used to set the support status for Web Sockets. Because these environment variable names are prefixed with “ASPNETCORE_”, they serve as the default configuration source. KestrelServer eventually binds to a local endpoint (“localhost”) based on that port for listening. Since the listening address is controlled by ASP.NET CORE Core Module, it only needs to forward the request to that address, and finally hand over the received response to IIS for return. Since local loopback access is involved here, its performance is naturally inferior to that of the In-Process deployment mode.

We demonstrated the deployment of In-Process above, now we directly modify the configuration file web.config, set the hostingModel property of the configuration section to “outofprocess” as above, and the deployed application will automatically switch to Out-of-Process. Accessing the deployed app again in the same way at this point, we will find that the process name displayed on the browser becomes “dotnet”.

Figure 4 The name of the process in Out-of-Process mode

The deployment mode can be defined directly in the project file, and if you set the AspNetCoreHostingModel property to “OutOfProcess” as follows, the settings for the deployment mode in the web.config generated after release will change accordingly. The default value of this property is “InProcess”, which we can also set explicitly.

To further verify the existence of this list of environment variables described above, the demo program shown below outputs the environment variables prefixed with “ASPNETCORE_” as the response content. In addition, the process name, the requested PathBase, and the MS-ASPNETCORE-TOKEN header are also output as the response.

After the application is republished, it is accessed again with the browser to get the result shown in Figure 5. We can find the above environment variables from here, the “MS-ASPNETCORE-TOKEN” header carried by the request coincides with the value of the corresponding environment variable, and the virtual directory applied in IIS is written to the environment variable as the application path and becomes the requested PathBase. If a site provides an HTTPS endpoint, its port also writes the environment variable “ASPNETCORE_ANCM_HTTPS_PORT”, which is designed to implement redirection to the HTTPS endpoint.

Figure 5 Environment variables in Out-of-Process mode

Most implementations of Out-of-Process deployments are done by the following IISMiddleware middleware, with IISOptions as the corresponding configuration option. IISMiddleware middleware completes the validation of “paired tokens” to filter non-IIS-forwarded requests. If the ForwardClientCertificate property of the IISOptions configuration option returns True (the default), this middleware extracts the client certificate from the request header “MS-ASPNETCORE-CLIENTCERT” and saves it to the ITlsConnectionFeature attribute. The middleware also attaches the Windows Principal object corresponding to the current Windows account to the HttpContext context’s feature collection, and if the AutomaticAuthentication property of the IISOptions configuration option returns True (the default), the object is assigned directly to the User property of the HttpContext context.

IIS utilizes WAS to activate the worker process w3wp upon request .exe. If the site has not been accessed for a long time, it also automatically shuts down the worker process. If the worker processes are closed, the dotnet ASP.NET process hosting the .exe CORE app should naturally shut down as well. To shut down the application hosting process, ASP.NET CORE Core Module sends a special request that carries an “MS-ASPNETCORE-EVENT” header with a value of “shutdown” that IISMiddleware uses the injected IHostApplicationLifeTime object to shut down the current application when it receives the request. If WebSocket is not supported, the middleware also removes the IHttpUpgradeFeature feature that stands for “upgradeable to two-way communication”. Setting the application path to the requested PathBase is also done by this middleware. Since the IISMiddleware middleware is actually doing the work of initializing the HttpContext context, it only makes sense that it must be executed first, in order to place this middleware at the front end of the pipeline, the following IISSetupFilter is defined to complete the registration of the middleware.

IISSetupFilter is ultimately registered through the IWebHostBuilder interface using the UseIISIntegration extension method below. This method is also responsible for extracting the port number from the current configuration and environment variables, and completing the registration of the listening address. Since KestrelServer chooses the endpoint registered on the server by default, the method uses the configuration to set the PreferHostingUrs property of the IServerAddressesFeature attribute to True, and the listening address set here takes effect. This method also sets IISOptions accordingly according to the settings of the current IIS site. Since the IHostBuider interface ConfigureWebHostDefaults extension method also calls this method internally, we don’t need to do extra work on it.

Regardless of the deployment mode, the configuration is defined in the web.config configuration file under the deployment directory, and the mapping provided for ASP.NET CORE Core Module allows us to deploy ASP.NET CORE applications in IIS. In web.config, the configuration related to ASP.NET CORE application deployment is defined in the configuration section.

attribute

Implications

processPath

ASP.NET the path where the CORE app launch command is located, required.

arguments

ASP.NET the parameters passed in by the CORE app startup, optionally.

stdoutLogEnabled

Whether stdout and stderr are output to the file specified by the stdoutLogFile attribute, defaults to False.

stdoutLogFile

Log files that are output as stdout and stderr default to “aspnetcore-stdout”.

hostingModel

Deployment mode, “inprocess/InProcess” or “outofprocess/OutOfProcess” (default).

forwardWindowsAuthToken

Whether to forward Windows authentication tokens, the default is True.

processesPerApplication

The number of processes hosting ASP.NET CORE app, which defaults to 1. This configuration is not valid for In-Process mode.

rapidFailsPerMinute

ASP.NET the number of crashes allowed per minute for the CORE app-hosted process (processPath) defaults to 10, beyond which it will no longer attempt to restart it.

requestTimeout

The request processing timeout is 2 minutes by default.

startupRetryCount

ASP.NET the number of CORE application hosting process startup retries, the default is 2 times.

startupTimeLimit

ASP.NET the CORE app hosting process startup timeout (in seconds), which defaults to 120 seconds.

environmentVariables

Set environment variables.

handlerSettings

Provides additional configurations for ASP.NET CORE Core Module.