ASP.NET Core 中文文檔 第三章 原理(14)服務器


原文:Servers
作者:Steve Smith
翻譯:謝煬(Kiler)
校對:許登洋(Seay)姚阿勇(Dr.Yao)

ASP.NET Core 已完全從承載應用程序的 Web 服務器環境中分離。ASP.NET Core 可以承載於 IIS 和 IIS Express ,以及使用 Kestrel 和 WebListener HTTP Server 的自承載環境中。此外,開發人員和第三方軟件供應商可以創建自定義的服務器來承載 ASP.NET Core 應用程序。

查看和下載示例代碼

服務器和命令

ASP.NET Core 旨在將 Web 應用程序從底層 HTTP 服務器分離出來。過去,ASP.NET 應用一直只在 Windows 中承載於 IIS 上。在 Windows 上運行 ASP.NET Core 應用程序的推薦方法是將 IIS 作為一個反向代理服務器來使用。IIS 中的 HttpPlatformHandler 模塊管理並分發請求給一個進程外的HTTP 服務器。ASP.NET Core 附帶兩個不同的 HTTP 服務器:

  • Microsoft.AspNetCore.Server.Kestrel (AKA Kestrel,跨平台)
  • Microsoft.AspNetCore.Server.WebListener (AKA WebListener,僅 Windows,預覽版)

ASP.NET Core 不直接監聽請求,而是依靠 HTTP 服務器的實現將請求作為組成 HttpContext 的一組功能接口暴露給應用程序。盡管 WebListener 只是 Window 專用的,但 Kestrel 則是被設計為跨平台運行的。你可以通過在 project.json 文件中指定命令來配置你的應用程序承載於任何一個或全部的服務器。你甚至可以為應用程序指定程序入口點,作為一個可執行文件運行(使用 dotnet run),而不是承載到不同的進程。

用 Visual Studio 開發的 ASP.NET 應用程序默認的 Web 托管服務器采用了 Kestrel 做反向代理服務器的 IIS Express, project.json 文件默認包含 “Microsoft.AspNetCore.Server.Kestrel” 和 “Microsoft.AspNetCore.Server.IISIntegration” 依賴,即使采用空網站模板。Visual Studio 也提供了多種方式來把網站關聯到 IISExpress。你可以在你的 web 應用程序項目的屬性菜單的 Debug 選項卡中或者 launchSettings.json 文件中管理這些配置和參數。
serverdemo-properties

本文的示例項目被配置成支持每個服務器的選項在 project.json 文件中:

{
  "webroot": "wwwroot",
  "version": "1.0.0-*",

  "dependencies": {
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-rc1-final"
  },

  "commands": {
    "run": "run server.urls=http://localhost:5003",
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5000",
    "weblistener": "Microsoft.AspNet.Hosting --server WebListener --server.urls http://localhost:5004"
  },

  "frameworks": {
    "dnx451": { },

run 命令會通過調用 void main 方法啟動應用程序。 run 命令配置和啟動一個 Kestrel 實例。

using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNet.Builder;
using Microsoft.Extensions.Logging;
using Microsoft.AspNet.Server.Kestrel;

namespace ServersDemo
{
    /// <summary>
    /// This demonstrates how the application can be launched in a console application. 
    /// Executing the "dnx run" command in the application folder will run this app.
    /// </summary>
    public class Program
    {
        private readonly IServiceProvider _serviceProvider;

        public Program(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public Task<int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var builder = new ConfigurationBuilder();
            builder.AddCommandLine(args);
            var config = builder.Build();

            using (new WebHostBuilder(config)
                .UseServer("Microsoft.AspNet.Server.Kestrel")
                .Build()
                .Start())
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return Task.FromResult(0);
        }
    }
}

服務支持的 Features

ASP.NET 定義了一系列 Request Features 。下表列出了所有 WebListener 和 Kestrel 支持 Features。

Feature WebListener Kestrel
IHttpRequestFeature
IHttpResponseFeature
IHttpAuthenticationFeature
IHttpUpgradeFeature 是(有限制)
IHttpBufferingFeature
IHttpConnectionFeature
IHttpRequestLifetimeFeature
IHttpSendFileFeature
IHttpWebSocketFeature 否* 否*
IRequestIdentifierFeature
ITlsConnectionFeature
ITlsTokenBindingFeature

配置選項

在服務器啟動時你可以提供可讀取的配置選項(命令行參數或配置文件)。

Microsoft.AspNetCore.Hosting 命令支持服務器參數(例如 Kestrel 或 WebListener )還有 server.urls 配置項。 server.urls 配置鍵值是一系列以分號分隔的服務器必須處理 URL 前綴列表。

上面的 project.json 文件演示了如何直接傳遞 server.urls 參數:

"web": "Microsoft.AspNetCore.Kestrel --server.urls http://localhost:5004"

另外,也可以使用 JSON 配置文件。

"kestrel": "Microsoft.AspNetCore.Hosting"

hosting.json 可以作為服務器設置的參數使用(也可以包括服務器參數):

{
  "server": "Microsoft.AspNetCore.Server.Kestrel",
  "server.urls": "http://localhost:5004/"
}

編碼化的配置

托管應用程序的服務器可以通過在 Startup 類的 Configure 方法中調用 IApplicationBuilder 接口來引用。 IApplicationBuilder 將服務器 Features 暴露為 IFeatureCollection 類型。IServerAddressesFeature 只公開了 Addresses 屬性,但不同的服務器實現可能會暴露更多的 Features ,例如,WebListener 公開了可用於配置服務器的認證的 AuthenticationManager :

public void Configure(IApplicationBuilder app, IApplicationLifetime lifetime, ILoggerFactory loggerFactory)
{
    var webListenerInfo = app.ServerFeatures.Get<WebListener>();
    if (webListenerInfo != null)
    {
        webListenerInfo.AuthenticationManager.AuthenticationSchemes =
            AuthenticationSchemes.AllowAnonymous;
    }

    var serverAddress = app.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses.FirstOrDefault();

    app.Run(async (context) =>
    {
        var message = String.Format("Hello World from {0}",
                                serverAddress);
        await context.Response.WriteAsync(message);
    });
}

IIS 與 IIS Express

IIS 是最功能豐富的應用服務器,包括 IIS 管理功能和訪問其他 IIS 模塊。托管 ASP.NET Core 不再使用由 ASP.NET 之前版本中使用的 System.Web 基礎庫。

ASP.NET Core 模塊

Windows 上的 ASP.NET Core , Web 應用程序宿主在 IIS 以外的進程上的。ASP.NET Core 模塊是一個原生的 IIS 模塊用來代理請求到管理的進程,更多參考 ASP.NET Core Module Configuration Reference 。

WebListener

WebListener 是 ASP.NET Core 的 Windows 專用 HTTP 服務器。它直接運行在 Http.Sys kernel driver之上,並且具有非常小的開銷。

你可以通過在 project.json 里面添加 “Microsoft.AspNetCore.Server.WebListener” 依賴以及下面的命令讓你的 ASP.NET 應用程序支持 WebListener :

"web": "Microsoft.AspNetCore.Hosting --server Microsoft.AspNetCore.Server.WebListener --server.urls http://localhost:5000"

提示
WebListener 還處於預覽版狀態。

Kestrel

Kestrel 是一個基於 libuv 的 Web 服務器,一個跨平台的異步 I/O 庫。你可以通過在 project.json 依賴列表中包含 Microsoft.AspNetCore.Server.Kestrel
 依賴來支持 Kestrel 。

了解更多關於創建 Kestrel 的細節 用 Visual Studio Code 在 macOS 上創建首個 ASP.NET Core 應用程序 。

提示
Kestrel 是設計在反向代理服務器(例如 IIS 或者 Nginx )之后的,並且不是直接面向 Internet 部署的。

服務器的選擇

如果你打算在 Windows 服務器上部署你的應用程序,你應該用 IIS 作為反向代理服務器來管理和代理發送到 Kestrel 的請求。如果在 Linux 上部署,你應該運行類似反向代理服務器,如 Apache 或 Nginx 的來代理發送到 Kestrel 的請求(更多參考 Publish to a Linux Production Environment )。

自定義服務器

你可以創建你自己的服務器中承載 ASP.NET 應用程序,或使用其他開源服務器。當你實現自己的服務器,你可以自由地實現只是你的應用程序的所需要 Feature 功能接口,不過至少需要支持IHttpRequestFeature 和 IHttpResponseFeature 。

因為 Kestrel 是開源的,如果你需要實現自己的自定義服務器,是一個不錯的起點。像所有的 ASP.NET Core,歡迎你 貢獻 自己的提交來回饋和改進這個項目。

Kestrel 當前支持有限數量的 Feature 接口,但是后續會增加更多 Features 支持。

附加閱讀

返回目錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM