ASP.NET Core 中的 HTTP.sys 網頁伺服器實作HTTP.sys web server implementation in ASP.NET Core

作者:Tom DykstraChris RossLuke LathamBy Tom Dykstra, Chris Ross, and Luke Latham

HTTP.sys 是只在 Windows 上執行的 ASP.NET Core 網頁伺服器HTTP.sys is a web server for ASP.NET Core that only runs on Windows. HTTP.sys 是 Kestrel 伺服器的替代方式,提供了一些 Kestrel 未提供的功能。HTTP.sys is an alternative to Kestrel server and offers some features that Kestrel doesn't provide.

重要

HTTP.sys 與 ASP.NET Core 模組不相容,且不能與 IIS 或 IIS Express 搭配使用。HTTP.sys isn't compatible with the ASP.NET Core Module and can't be used with IIS or IIS Express.

HTTP.sys 支援下列功能:HTTP.sys supports the following features:

  • Windows 驗證Windows Authentication
  • 連接埠共用Port sharing
  • 使用 SNI 的 HTTPSHTTPS with SNI
  • 透過 TLS 的 HTTP/2 (Windows 10 或更新版本)HTTP/2 over TLS (Windows 10 or later)
  • 直接檔案傳輸Direct file transmission
  • 回應快取Response caching
  • WebSocket (Windows 8 或更新版本)WebSockets (Windows 8 or later)

支援的 Windows 版本:Supported Windows versions:

  • Windows 7 或更新版本Windows 7 or later
  • Windows Server 2008 R2 或更新版本Windows Server 2008 R2 or later

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

使用 HTTP.sys 的時機When to use HTTP.sys

HTTP.sys 在下列部署環境中非常有用:HTTP.sys is useful for deployments where:

  • 需要直接向網際網路公開伺服器而不使用 IIS。There's a need to expose the server directly to the Internet without using IIS.

    HTTP.sys 直接與網際網路通訊

  • 內部部署需要的功能無法在 Kestrel 中使用,例如 Windows 驗證An internal deployment requires a feature not available in Kestrel, such as Windows Authentication.

    HTTP.sys 直接與內部網路通訊

HTTP.sys 是成熟的技術,可抵禦許多種類的攻擊,並提供功能完整之網頁伺服器的穩固性、安全性及延展性。HTTP.sys is mature technology that protects against many types of attacks and provides the robustness, security, and scalability of a full-featured web server. IIS 本身在 HTTP.sys 之上以 HTTP 接聽程式的形式執行。IIS itself runs as an HTTP listener on top of HTTP.sys.

HTTP/2 支援HTTP/2 support

如果符合下列基本需求,則可以針對 ASP.NET Core 應用程式啟用 HTTP/2HTTP/2 is enabled for ASP.NET Core apps if the following base requirements are met:

如果已建立 HTTP/2 連線,HttpRequest.Protocol 會報告 HTTP/2If an HTTP/2 connection is established, HttpRequest.Protocol reports HTTP/2.

如果已建立 HTTP/2 連線,HttpRequest.Protocol 會報告 HTTP/1.1If an HTTP/2 connection is established, HttpRequest.Protocol reports HTTP/1.1.

HTTP/2 預設為啟用。HTTP/2 is enabled by default. 如果 HTTP/2 連線尚未建立,連線會退為 HTTP/1.1。If an HTTP/2 connection isn't established, the connection falls back to HTTP/1.1. Windows 的未來版本會推出 HTTP/2 設定旗標,包括使用 HTTP.sys 來停用 HTTP/2 的功能。In a future release of Windows, HTTP/2 configuration flags will be available, including the ability to disable HTTP/2 with HTTP.sys.

使用 Kerberos 的核心模式驗證Kernel mode authentication with Kerberos

HTTP.sys 使用 Kerberos 驗證通訊協定委派給核心模式驗證。HTTP.sys delegates to kernel mode authentication with the Kerberos authentication protocol. Kerberos 和 HTTP.sys 不支援使用者模式驗證。User mode authentication isn't supported with Kerberos and HTTP.sys. 必須使用電腦帳戶來解密 Kerberos 權杖/票證,該權杖/票證取自 Active Directory,並由用戶端將其轉送至伺服器來驗證使用者。The machine account must be used to decrypt the Kerberos token/ticket that's obtained from Active Directory and forwarded by the client to the server to authenticate the user. 請註冊主機的服務主體名稱 (SPN),而非應用程式的使用者。Register the Service Principal Name (SPN) for the host, not the user of the app.

如何使用 HTTP.sysHow to use HTTP.sys

設定 ASP.NET Core 應用程式使用 HTTP.sysConfigure the ASP.NET Core app to use HTTP.sys

使用AspNetCore 應用程式中繼套件nuget.org)時,不需要專案檔中的套件參考。A package reference in the project file isn't required when using the Microsoft.AspNetCore.App metapackage (nuget.org). 若不是使用 Microsoft.AspNetCore.App 中繼套件,請將套件參考加入 Microsoft.AspNetCore.Server.HttpSysWhen not using the Microsoft.AspNetCore.App metapackage, add a package reference to Microsoft.AspNetCore.Server.HttpSys.

建置主機時,呼叫 UseHttpSys 擴充方法,並指定任何必要的 HttpSysOptionsCall the UseHttpSys extension method when building the host, specifying any required HttpSysOptions. 下列範例會將選項設定為它們的預設值:The following example sets options to their default values:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseHttpSys(options =>
            {
                options.AllowSynchronousIO = true;
                options.Authentication.Schemes = AuthenticationSchemes.None;
                options.Authentication.AllowAnonymous = true;
                options.MaxConnections = null;
                options.MaxRequestBodySize = 30000000;
                options.UrlPrefixes.Add("http://localhost:5005");
            });
            webBuilder.UseStartup<Startup>();
        });
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseHttpSys(options =>
        {
            options.AllowSynchronousIO = true;
            options.Authentication.Schemes = AuthenticationSchemes.None;
            options.Authentication.AllowAnonymous = true;
            options.MaxConnections = null;
            options.MaxRequestBodySize = 30000000;
            options.UrlPrefixes.Add("http://localhost:5000");
        });

其他的 HTTP.sys 設定則透過登錄設定處理。Additional HTTP.sys configuration is handled through registry settings.

HTTP.sys 選項HTTP.sys options

屬性Property 描述Description DefaultDefault
AllowSynchronousIOAllowSynchronousIO 控制是否允許 HttpContext.Request.BodyHttpContext.Response.Body 同步輸出/輸入。Control whether synchronous input/output is allowed for the HttpContext.Request.Body and HttpContext.Response.Body. false
Authentication.AllowAnonymousAuthentication.AllowAnonymous 允許匿名要求。Allow anonymous requests. true
Authentication.SchemesAuthentication.Schemes 指定允許的驗證配置。Specify the allowed authentication schemes. 處置接聽程式之前可隨時修改。May be modified at any time prior to disposing the listener. 值是由 AuthenticationSchemes enum 提供:BasicKerberosNegotiateNoneNTLMValues are provided by the AuthenticationSchemes enum: Basic, Kerberos, Negotiate, None, and NTLM. None
EnableResponseCachingEnableResponseCaching 針對含有合格標頭的回應嘗試核心模式快取。Attempt kernel-mode caching for responses with eligible headers. 回應可能不包含 Set-CookieVaryPragma 標頭。The response may not include Set-Cookie, Vary, or Pragma headers. 它必須包含為 publicCache-Control 標頭,且有 shared-max-agemax-age 值,或是 Expires 標頭。It must include a Cache-Control header that's public and either a shared-max-age or max-age value, or an Expires header. true
MaxAccepts 可同時接受的數目上限。The maximum number of concurrent accepts. 5 × Environment.
ProcessorCount
5 × Environment.
ProcessorCount
MaxConnections 可接受的同時連線數量上限。The maximum number of concurrent connections to accept. 使用 -1 為無限多個。Use -1 for infinite. 使用 null 以使用登錄之整個電腦的設定。Use null to use the registry's machine-wide setting. null
(全電腦(machine-wide
setting)
MaxRequestBodySize 請參閱 MaxRequestBodySize 小節。See the MaxRequestBodySize section. 30000000 位元組30000000 bytes
(~28.6 MB)(~28.6 MB)
RequestQueueLimit 可以加入佇列的最大要求數目。The maximum number of requests that can be queued. 10001000
RequestQueueMode 這會指出伺服器是否負責建立和設定要求佇列,或是否應附加至現有的佇列。This indicates whether the server is responsible for creating and configuring the request queue, or if it should attach to an existing queue.
附加至現有的佇列時,大部分的現有設定選項都不適用。Most existing configuration options do not apply when attaching to an existing queue.
RequestQueueMode.Create
RequestQueueName Http.sys 要求佇列的名稱。The name of the HTTP.sys request queue. null (匿名佇列)null (Anonymous queue)
ThrowWriteExceptions 指出若回應本文因為用戶端中斷連線而寫入失敗時,應擲回例外狀況或正常完成。Indicate if response body writes that fail due to client disconnects should throw exceptions or complete normally. false
(正常完成)(complete normally)
Timeouts 公開 HTTP.sys TimeoutManager 設定,這也可在登錄中設定。Expose the HTTP.sys TimeoutManager configuration, which may also be configured in the registry. API 連結可提供包括預設值在內每個設定的詳細資訊:Follow the API links to learn more about each setting, including default values:
UrlPrefixes 指定 UrlPrefixCollection 以向 HTTP.sys 註冊。Specify the UrlPrefixCollection to register with HTTP.sys. 最實用的是 UrlPrefixCollection.Add,可用來將前置詞加入集合。The most useful is UrlPrefixCollection.Add, which is used to add a prefix to the collection. 處置接聽程式之前可隨時修改這些內容。These may be modified at any time prior to disposing the listener.
屬性Property 描述Description DefaultDefault
AllowSynchronousIOAllowSynchronousIO 控制是否允許 HttpContext.Request.BodyHttpContext.Response.Body 同步輸出/輸入。Control whether synchronous input/output is allowed for the HttpContext.Request.Body and HttpContext.Response.Body. false
Authentication.AllowAnonymousAuthentication.AllowAnonymous 允許匿名要求。Allow anonymous requests. true
Authentication.SchemesAuthentication.Schemes 指定允許的驗證配置。Specify the allowed authentication schemes. 處置接聽程式之前可隨時修改。May be modified at any time prior to disposing the listener. 值是由 AuthenticationSchemes enum 提供:BasicKerberosNegotiateNoneNTLMValues are provided by the AuthenticationSchemes enum: Basic, Kerberos, Negotiate, None, and NTLM. None
EnableResponseCachingEnableResponseCaching 針對含有合格標頭的回應嘗試核心模式快取。Attempt kernel-mode caching for responses with eligible headers. 回應可能不包含 Set-CookieVaryPragma 標頭。The response may not include Set-Cookie, Vary, or Pragma headers. 它必須包含為 publicCache-Control 標頭,且有 shared-max-agemax-age 值,或是 Expires 標頭。It must include a Cache-Control header that's public and either a shared-max-age or max-age value, or an Expires header. true
MaxAccepts 可同時接受的數目上限。The maximum number of concurrent accepts. 5 × Environment.
ProcessorCount
5 × Environment.
ProcessorCount
MaxConnections 可接受的同時連線數量上限。The maximum number of concurrent connections to accept. 使用 -1 為無限多個。Use -1 for infinite. 使用 null 以使用登錄之整個電腦的設定。Use null to use the registry's machine-wide setting. null
(全電腦(machine-wide
setting)
MaxRequestBodySize 請參閱 MaxRequestBodySize 小節。See the MaxRequestBodySize section. 30000000 位元組30000000 bytes
(~28.6 MB)(~28.6 MB)
RequestQueueLimit 可以加入佇列的最大要求數目。The maximum number of requests that can be queued. 10001000
ThrowWriteExceptions 指出若回應本文因為用戶端中斷連線而寫入失敗時,應擲回例外狀況或正常完成。Indicate if response body writes that fail due to client disconnects should throw exceptions or complete normally. false
(正常完成)(complete normally)
Timeouts 公開 HTTP.sys TimeoutManager 設定,這也可在登錄中設定。Expose the HTTP.sys TimeoutManager configuration, which may also be configured in the registry. API 連結可提供包括預設值在內每個設定的詳細資訊:Follow the API links to learn more about each setting, including default values:
UrlPrefixes 指定 UrlPrefixCollection 以向 HTTP.sys 註冊。Specify the UrlPrefixCollection to register with HTTP.sys. 最實用的是 UrlPrefixCollection.Add,可用來將前置詞加入集合。The most useful is UrlPrefixCollection.Add, which is used to add a prefix to the collection. 處置接聽程式之前可隨時修改這些內容。These may be modified at any time prior to disposing the listener.
屬性Property 描述Description DefaultDefault
AllowSynchronousIOAllowSynchronousIO 控制是否允許 HttpContext.Request.BodyHttpContext.Response.Body 同步輸出/輸入。Control whether synchronous input/output is allowed for the HttpContext.Request.Body and HttpContext.Response.Body. true
Authentication.AllowAnonymousAuthentication.AllowAnonymous 允許匿名要求。Allow anonymous requests. true
Authentication.SchemesAuthentication.Schemes 指定允許的驗證配置。Specify the allowed authentication schemes. 處置接聽程式之前可隨時修改。May be modified at any time prior to disposing the listener. 值是由 AuthenticationSchemes enum 提供:BasicKerberosNegotiateNoneNTLMValues are provided by the AuthenticationSchemes enum: Basic, Kerberos, Negotiate, None, and NTLM. None
EnableResponseCachingEnableResponseCaching 針對含有合格標頭的回應嘗試核心模式快取。Attempt kernel-mode caching for responses with eligible headers. 回應可能不包含 Set-CookieVaryPragma 標頭。The response may not include Set-Cookie, Vary, or Pragma headers. 它必須包含為 publicCache-Control 標頭,且有 shared-max-agemax-age 值,或是 Expires 標頭。It must include a Cache-Control header that's public and either a shared-max-age or max-age value, or an Expires header. true
MaxAccepts 可同時接受的數目上限。The maximum number of concurrent accepts. 5 × Environment.
ProcessorCount
5 × Environment.
ProcessorCount
MaxConnections 可接受的同時連線數量上限。The maximum number of concurrent connections to accept. 使用 -1 為無限多個。Use -1 for infinite. 使用 null 以使用登錄之整個電腦的設定。Use null to use the registry's machine-wide setting. null
(全電腦(machine-wide
setting)
MaxRequestBodySize 請參閱 MaxRequestBodySize 小節。See the MaxRequestBodySize section. 30000000 位元組30000000 bytes
(~28.6 MB)(~28.6 MB)
RequestQueueLimit 可以加入佇列的最大要求數目。The maximum number of requests that can be queued. 10001000
ThrowWriteExceptions 指出若回應本文因為用戶端中斷連線而寫入失敗時,應擲回例外狀況或正常完成。Indicate if response body writes that fail due to client disconnects should throw exceptions or complete normally. false
(正常完成)(complete normally)
Timeouts 公開 HTTP.sys TimeoutManager 設定,這也可在登錄中設定。Expose the HTTP.sys TimeoutManager configuration, which may also be configured in the registry. API 連結可提供包括預設值在內每個設定的詳細資訊:Follow the API links to learn more about each setting, including default values:
UrlPrefixes 指定 UrlPrefixCollection 以向 HTTP.sys 註冊。Specify the UrlPrefixCollection to register with HTTP.sys. 最實用的是 UrlPrefixCollection.Add,可用來將前置詞加入集合。The most useful is UrlPrefixCollection.Add, which is used to add a prefix to the collection. 處置接聽程式之前可隨時修改這些內容。These may be modified at any time prior to disposing the listener.

MaxRequestBodySizeMaxRequestBodySize

任何要求所允許的大小上限 (以位元組為單位)。The maximum allowed size of any request body in bytes. 當設定為 null 時,要求主體大小上限為無限制。When set to null, the maximum request body size is unlimited. 此限制對升級連線不會有任何影響,因為其一律為無限制。This limit has no effect on upgraded connections, which are always unlimited.

在 ASP.NET Core MVC 應用程式中針對單一 IActionResult 覆寫限制的建議方式,是在動作方法上使用 RequestSizeLimitAttribute 屬性:The recommended method to override the limit in an ASP.NET Core MVC app for a single IActionResult is to use the RequestSizeLimitAttribute attribute on an action method:

[RequestSizeLimit(100000000)]
public IActionResult MyActionMethod()

如果應用程式已開始讀取要求之後,才嘗試設定要求的限制,則會擲回例外狀況。An exception is thrown if the app attempts to configure the limit on a request after the app has started reading the request. IsReadOnly 屬性可用來指出 MaxRequestBodySize 屬性是否處於唯讀狀態,代表要設定限制已經太遲。An IsReadOnly property can be used to indicate if the MaxRequestBodySize property is in a read-only state, meaning it's too late to configure the limit.

如果應用程式應該覆寫每個要求的 MaxRequestBodySize,請使用 IHttpMaxRequestBodySizeFeatureIf the app should override MaxRequestBodySize per-request, use the IHttpMaxRequestBodySizeFeature:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, 
    ILogger<Startup> logger, IServer server)
{
    app.Use(async (context, next) =>
    {
        context.Features.Get<IHttpMaxRequestBodySizeFeature>()
            .MaxRequestBodySize = 10 * 1024;

        var serverAddressesFeature = 
            app.ServerFeatures.Get<IServerAddressesFeature>();
        var addresses = string.Join(", ", serverAddressesFeature?.Addresses);

        logger.LogInformation("Addresses: {Addresses}", addresses);

        await next.Invoke();
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILogger<Startup> logger, IServer server)
{
    app.Use(async (context, next) =>
    {
        context.Features.Get<IHttpMaxRequestBodySizeFeature>()
            .MaxRequestBodySize = 10 * 1024;

        var serverAddressesFeature = 
            app.ServerFeatures.Get<IServerAddressesFeature>();
        var addresses = string.Join(", ", serverAddressesFeature?.Addresses);

        logger.LogInformation("Addresses: {Addresses}", addresses);

        await next.Invoke();
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    // Enable HTTPS Redirection Middleware when hosting the app securely.
    //app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseMvc();
}

如果您使用 Visual Studio,請確定應用程式未設定為執行 IIS 或 IIS Express。If using Visual Studio, make sure the app isn't configured to run IIS or IIS Express.

在 Visual Studio 中,預設啟動設定檔適用於 IIS Express。In Visual Studio, the default launch profile is for IIS Express. 若要執行專案作為主控台應用程式,請手動變更選取的設定檔,如下列螢幕擷取畫面所示:To run the project as a console app, manually change the selected profile, as shown in the following screen shot:

選取主控台應用程式設定檔

設定 Windows ServerConfigure Windows Server

  1. 判斷要為應用程式開啟的連接埠,然後使用 Windows 防火牆New-NetFirewallRule PowerShell Cmdlet 來開啟防火牆連接埠,以允許流量到達 HTTP.sys。Determine the ports to open for the app and use Windows Firewall or the New-NetFirewallRule PowerShell cmdlet to open firewall ports to allow traffic to reach HTTP.sys. 在下列命令和應用程式設定中,會使用連接埠 443。In the following commands and app configuration, port 443 is used.

  2. 部署至 Azure VM 時,請在網路安全性群組中開啟連接埠。When deploying to an Azure VM, open the ports in the Network Security Group. 在下列命令和應用程式設定中,會使用連接埠 443。In the following commands and app configuration, port 443 is used.

  3. 視需要取得並安裝 X.509 憑證。Obtain and install X.509 certificates, if required.

    在 Windows 上,請使用 New-SelfSignedCertificate PowerShell Cmdlet 來建立自我簽署的憑證。On Windows, create self-signed certificates using the New-SelfSignedCertificate PowerShell cmdlet. 如需不支援的範例,請參閱 UpdateIISExpressSSLForChrome.ps1 (英文)。For an unsupported example, see UpdateIISExpressSSLForChrome.ps1.

    將自我簽署的憑證或 CA 簽署的憑證安裝在伺服器的 [本機電腦] > 個人 存放區中。Install either self-signed or CA-signed certificates in the server's Local Machine > Personal store.

  4. 如果應用程式是與架構相依的部署,請安裝 .NET Core、.NET Framework 或兩者 (如果應用程式是以 .NET Framework 為目標的 .NET Core 應用程式)。If the app is a framework-dependent deployment, install .NET Core, .NET Framework, or both (if the app is a .NET Core app targeting the .NET Framework).

    • .NET Core – 如果應用程式需要 .NET Core,請從 .NET Core 下載取得並執行 .NET Core 執行階段安裝程式。.NET Core – If the app requires .NET Core, obtain and run the .NET Core Runtime installer from .NET Core Downloads. 請勿在伺服器上安裝完整的 SDK。Don't install the full SDK on the server.
    • .NET Framework – 如果應用程式需要 .NET Framework,請參閱 .NET Framework 安裝指南.NET Framework – If the app requires .NET Framework, see the .NET Framework installation guide. 安裝必要的 .NET Framework。Install the required .NET Framework. 您可以從 .NET Core 下載頁面取得最新 .NET Framework 的安裝程式。The installer for the latest .NET Framework is available from the .NET Core Downloads page.

    如果應用程式是自封式部署,則應用程式的部署中會包含執行階段。If the app is a self-contained deployment, the app includes the runtime in its deployment. 不需要在伺服器上安裝任何架構。No framework installation is required on the server.

  5. 設定應用程式中的 URL 和連接埠。Configure URLs and ports in the app.

    ASP.NET Core 預設會繫結至 http://localhost:5000By default, ASP.NET Core binds to http://localhost:5000. 若要設定 URL 首碼和連接埠,選項包括:To configure URL prefixes and ports, options include:

    • UseUrls
    • urls 命令列引數urls command-line argument
    • ASPNETCORE_URLS 環境變數ASPNETCORE_URLS environment variable
    • UrlPrefixes

    下列程式碼範例示範如何使用 UrlPrefixes 搭配位於連接埠 443 的伺服器本機 IP 位址 10.0.0.4The following code example shows how to use UrlPrefixes with the server's local IP address 10.0.0.4 on port 443:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseHttpSys(options =>
            {
                options.UrlPrefixes.Add("https://10.0.0.4:443");
            });
            webBuilder.UseStartup<Startup>();
        });
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseHttpSys(options =>
        {
            options.UrlPrefixes.Add("https://10.0.0.4:443");
        });

UrlPrefixes 的優點是針對錯誤格式的前置詞會立即產生錯誤訊息。An advantage of UrlPrefixes is that an error message is generated immediately for improperly formatted prefixes.

UrlPrefixes 中的設定會覆寫 UseUrls/urls/ASPNETCORE_URLS 設定。The settings in UrlPrefixes override UseUrls/urls/ASPNETCORE_URLS settings. 因此,UseUrlsurlsASPNETCORE_URLS 環境變數的優點,是能更輕鬆地在 Kestrel 和 HTTP.sys 之間切換。Therefore, an advantage of UseUrls, urls, and the ASPNETCORE_URLS environment variable is that it's easier to switch between Kestrel and HTTP.sys.

HTTP.sys 使用 HTTP Server API UrlPrefix 字串格式HTTP.sys uses the HTTP Server API UrlPrefix string formats.

警告

使用最上層萬用字元繫結 (http://*:80/http://+:80)。Top-level wildcard bindings (http://*:80/ and http://+:80) should not be used. 最上層萬用字元繫結會導致應用程式安全性弱點。Top-level wildcard bindings create app security vulnerabilities. 這對強式與弱式萬用字元皆適用。This applies to both strong and weak wildcards. 請使用明確的主機名稱或 IP 位址,而不要使用萬用字元。Use explicit host names or IP addresses rather than wildcards. 若您擁有整個父網域 (相對於有弱點的 *.com) 的控制權,則子網域萬用字元繫結 (例如 *.mysub.com) 便不構成安全性風險。Subdomain wildcard binding (for example, *.mysub.com) isn't a security risk if you control the entire parent domain (as opposed to *.com, which is vulnerable). 如需詳細資訊,請參閱RFC 7230:第5.4 節:主機For more information, see RFC 7230: Section 5.4: Host.

  1. 在伺服器上預先註冊 URL 首碼。Preregister URL prefixes on the server.

    用來設定 HTTP.sys 的內建工具是 netsh.exeThe built-in tool for configuring HTTP.sys is netsh.exe. netsh.exe 是用來保留 URL 前置詞,並指派 X.509 憑證。netsh.exe is used to reserve URL prefixes and assign X.509 certificates. 此工具需要系統管理員權限。The tool requires administrator privileges.

    使用 netsh.exe 工具來為應用程式註冊 URL:Use the netsh.exe tool to register URLs for the app:

    netsh http add urlacl url=<URL> user=<USER>
    
    • <URL> – 完整的「統一資源定位器」(URL)。<URL> – The fully qualified Uniform Resource Locator (URL). 請勿使用萬用字元繫結。Don't use a wildcard binding. 請使用有效的主機名稱或本機 IP 位址。Use a valid hostname or local IP address. URL 必須包含結尾斜線。The URL must include a trailing slash.
    • <USER> – 會指定使用者或「使用者-群組」名稱。<USER> – Specifies the user or user-group name.

    在以下範例中,伺服器的本機 IP 位址是 10.0.0.4In the following example, the local IP address of the server is 10.0.0.4:

    netsh http add urlacl url=https://10.0.0.4:443/ user=Users
    

    已註冊 URL 時,此工具會以 URL reservation successfully added 回應。When a URL is registered, the tool responds with URL reservation successfully added.

    若要刪除已註冊的 URL,請使用 delete urlacl 命令:To delete a registered URL, use the delete urlacl command:

    netsh http delete urlacl url=<URL>
    
  2. 在伺服器上註冊 X.509 憑證。Register X.509 certificates on the server.

    使用 netsh.exe 工具來為應用程式註冊憑證:Use the netsh.exe tool to register certificates for the app:

    netsh http add sslcert ipport=<IP>:<PORT> certhash=<THUMBPRINT> appid="{<GUID>}"
    
    • <IP> – 會指定繫結的本機 IP 位址。<IP> – Specifies the local IP address for the binding. 請勿使用萬用字元繫結。Don't use a wildcard binding. 請使用有效的 IP 位址。Use a valid IP address.
    • <PORT> – 會指定繫結的連接埠。<PORT> – Specifies the port for the binding.
    • <THUMBPRINT> – X.509 憑證指紋。<THUMBPRINT> – The X.509 certificate thumbprint.
    • <GUID> – 開發人員所產生來代表應用程式的 GUID,供參考使用。<GUID> – A developer-generated GUID to represent the app for informational purposes.

    為了便於參考,請將 GUID 以套件標記的形式儲存在應用程式中:For reference purposes, store the GUID in the app as a package tag:

    • 在 Visual Studio 中:In Visual Studio:
      • 在 [方案總管] 中的專案上按一下滑鼠右鍵,然後選取 [屬性],以開啟應用程式的專案屬性。Open the app's project properties by right-clicking on the app in Solution Explorer and selecting Properties.
      • 選取 [套件] 索引標籤。Select the Package tab.
      • 輸入您在 [標記] 欄位中建立的 GUID。Enter the GUID that you created in the Tags field.
    • 不是使用 Visual Studio 時:When not using Visual Studio:
      • 開啟應用程式的專案檔。Open the app's project file.

      • <PackageTags> 屬性搭配您所建立的 GUID 新增至新的或現有的 <PropertyGroup>Add a <PackageTags> property to a new or existing <PropertyGroup> with the GUID that you created:

        <PropertyGroup>
          <PackageTags>9412ee86-c21b-4eb8-bd89-f650fbf44931</PackageTags>
        </PropertyGroup>
        

    在以下範例中:In the following example:

    • 伺服器的本機 IP 位址是 10.0.0.4The local IP address of the server is 10.0.0.4.
    • 線上隨機 GUID 產生器會提供 appid 值。An online random GUID generator provides the appid value.
    netsh http add sslcert 
        ipport=10.0.0.4:443 
        certhash=b66ee04419d4ee37464ab8785ff02449980eae10 
        appid="{9412ee86-c21b-4eb8-bd89-f650fbf44931}"
    

    已註冊憑證時,此工具會以 SSL Certificate successfully added 回應。When a certificate is registered, the tool responds with SSL Certificate successfully added.

    若要刪除憑證註冊,請使用 delete sslcert 命令:To delete a certificate registration, use the delete sslcert command:

    netsh http delete sslcert ipport=<IP>:<PORT>
    

    以下是 netsh.exe 的參考文件:Reference documentation for netsh.exe:

  3. 執行應用程式。Run the app.

    使用 HTTP (不是 HTTPS) 搭配大於 1024 的連接埠號碼來繫結至 localhost 時,不需要系統管理員權限即可執行應用程式。Administrator privileges aren't required to run the app when binding to localhost using HTTP (not HTTPS) with a port number greater than 1024. 針對其他設定 (例如,使用本機 IP 位址或繫結至連接埠 443),請使用系統管理員權限來執行應用程式。For other configurations (for example, using a local IP address or binding to port 443), run the app with administrator privileges.

    應用程式會在伺服器的公用 IP 位址回應。The app responds at the server's public IP address. 在此範例中,是從網際網路透過伺服器的公用 IP 位址 104.214.79.47 連線至伺服器。In this example, the server is reached from the Internet at its public IP address of 104.214.79.47.

    在此範例中使用的是開發憑證。A development certificate is used in this example. 在略過瀏覽器的未受信任憑證警告之後,頁面會安全地載入。The page loads securely after bypassing the browser's untrusted certificate warning.

    顯示已載入應用程式索引頁面的瀏覽器視窗

Proxy 伺服器和負載平衡器案例Proxy server and load balancer scenarios

如果是 HTTP.sys 所裝載且與來自網際網路或公司網路的要求進行互動的應用程式,在裝載於 Proxy 伺服器和負載平衡器後方時,可能需要額外的組態。For apps hosted by HTTP.sys that interact with requests from the Internet or a corporate network, additional configuration might be required when hosting behind proxy servers and load balancers. 如需詳細資訊,請參閱設定 ASP.NET Core 以處理 Proxy 伺服器和負載平衡器For more information, see Configure ASP.NET Core to work with proxy servers and load balancers.

其他資源Additional resources