ASP.NET Core Web 主機ASP.NET Core Web Host

作者:Luke LathamBy Luke Latham

ASP.NET Core 應用程式會設定並啟動「主機」 。ASP.NET Core apps configure and launch a host. 主機負責應用程式啟動和存留期管理。The host is responsible for app startup and lifetime management. 至少,主機會設定伺服器和要求處理管線。At a minimum, the host configures a server and a request processing pipeline. 主機也可以設定記錄、相依性插入和設定。The host can also set up logging, dependency injection, and configuration.

此文章涵蓋 Web 主機,而且我們僅因為回溯相容性而繼續提供它。This article covers the Web Host, which remains available only for backward compatibility. 建議為所有應用程式類型使用一般主機The Generic Host is recommended for all app types.

此文章涵蓋 Web 主機,它適用於裝載 Web 應用程式。This article covers the Web Host, which is for hosting web apps. 針對其他類型的應用程式,請使用一般主機For other kinds of apps, use the Generic Host.

設定主機Set up a host

使用 (IWebHostBuilder) 的執行個體建立主機。Create a host using an instance of IWebHostBuilder. 這通常在應用程式的進入點執行,也就是 Main 方法。This is typically performed in the app's entry point, the Main method.

在專案範本中,Main 位於 Program.csIn the project templates, Main is located in Program.cs. 一般的應用程式會呼叫 CreateDefaultBuilder 來開始設定主機:A typical app calls CreateDefaultBuilder to start setting up a host:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

呼叫 CreateDefaultBuilder 的程式碼位於名為 CreateWebHostBuilder 的方法中,這將它與 Main 中呼叫產生器物件上之 Run 的方法分開。The code that calls CreateDefaultBuilder is in a method named CreateWebHostBuilder, which separates it from the code in Main that calls Run on the builder object. 若您使用e Entity Framework Core 工具,則此分開是必要的。This separation is required if you use Entity Framework Core tools. 工具預期找到它們可以在設計階段呼叫的 CreateWebHostBuilder 方法,以在不執行應用程式的情況下設定主機。The tools expect to find a CreateWebHostBuilder method that they can call at design time to configure the host without running the app. 替代方式是實作 IDesignTimeDbContextFactoryAn alternative is to implement IDesignTimeDbContextFactory. 如需詳細資訊,請參閱設計階段 DbContext 建立For more information, see Design-time DbContext Creation.

CreateDefaultBuilder 會執行下列工作:CreateDefaultBuilder performs the following tasks:

CreateDefaultBuilder 所定義的組態可以透過 ConfigureAppConfigurationConfigureLogging,以及 IWebHostBuilder 的其他方法和擴充方法加以覆寫及擴增。The configuration defined by CreateDefaultBuilder can be overridden and augmented by ConfigureAppConfiguration, ConfigureLogging, and other methods and extension methods of IWebHostBuilder. 數個範例如下:A few examples follow:

  • ConfigureAppConfiguration 用來指定應用程式的其他 IConfigurationConfigureAppConfiguration is used to specify additional IConfiguration for the app. 下列 ConfigureAppConfiguration 呼叫會新增委派,以在 appsettings.xml 檔案中包含應用程式組態。The following ConfigureAppConfiguration call adds a delegate to include app configuration in the appsettings.xml file. 可能會多次呼叫 ConfigureAppConfigurationConfigureAppConfiguration may be called multiple times. 請注意,此組態不適用於主機 (例如,伺服器 URL 或環境)。Note that this configuration doesn't apply to the host (for example, server URLs or environment). 請參閱主機組態值一節。See the Host configuration values section.

    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddXmlFile("appsettings.xml", optional: true, reloadOnChange: true);
        })
        ...
    
  • 下列 ConfigureLogging 呼叫會新增委派,將最低的記錄層級 (SetMinimumLevel) 設定為 LogLevel.WarningThe following ConfigureLogging call adds a delegate to configure the minimum logging level (SetMinimumLevel) to LogLevel.Warning. 此設定會覆寫 CreateDefaultBuilder 所設定之 ppsettings.Development.json (LogLevel.Debug) 和 appsettings.Production.json (LogLevel.Error) 中的設定。This setting overrides the settings in appsettings.Development.json (LogLevel.Debug) and appsettings.Production.json (LogLevel.Error) configured by CreateDefaultBuilder. 可能會多次呼叫 ConfigureLoggingConfigureLogging may be called multiple times.

    WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging(logging => 
        {
            logging.SetMinimumLevel(LogLevel.Warning);
        })
        ...
    
  • 下列 ConfigureKestrel 呼叫會覆寫當 CreateDefaultBuilder 設定 Kestrel 時建立的預設 Limits.MaxRequestBodySize 30,000,000 位元組:The following call to ConfigureKestrel overrides the default Limits.MaxRequestBodySize of 30,000,000 bytes established when Kestrel was configured by CreateDefaultBuilder:

    WebHost.CreateDefaultBuilder(args)
        .ConfigureKestrel((context, options) =>
        {
            options.Limits.MaxRequestBodySize = 20000000;
        });
    
  • 下列 UseKestrel 呼叫會覆寫當 CreateDefaultBuilder 設定 Kestrel 時建立的預設 Limits.MaxRequestBodySize 30,000,000 位元組:The following call to UseKestrel overrides the default Limits.MaxRequestBodySize of 30,000,000 bytes established when Kestrel was configured by CreateDefaultBuilder:

    WebHost.CreateDefaultBuilder(args)
        .UseKestrel(options =>
        {
            options.Limits.MaxRequestBodySize = 20000000;
        });
    

「內容根目錄」 會決定主機搜尋內容檔案 (例如 MVC 檢視檔案) 的位置。The content root determines where the host searches for content files, such as MVC view files. 從專案的根資料夾啟動應用程式時,會使用專案的根資料夾作為內容根目錄。When the app is started from the project's root folder, the project's root folder is used as the content root. 這是 Visual Studiodotnet 新範本中使用的預設值。This is the default used in Visual Studio and the dotnet new templates.

如需應用程式組態的詳細資訊,請參閱 ASP.NET Core 的設定For more information on app configuration, see ASP.NET Core 的設定.

注意

作為使用靜態 CreateDefaultBuilder 方法的替代做法,ASP.NET Core 2.x 支援從 WebHostBuilder 建立主機的方法。As an alternative to using the static CreateDefaultBuilder method, creating a host from WebHostBuilder is a supported approach with ASP.NET Core 2.x.

設定主機時,可以提供 ConfigureConfigureServices 方法。When setting up a host, Configure and ConfigureServices methods can be provided. 如果指定 Startup 類別,它必須定義 Configure 方法。If a Startup class is specified, it must define a Configure method. 如需詳細資訊,請參閱 ASP.NET Core 中的應用程式啟動For more information, see ASP.NET Core 中的應用程式啟動. 多次呼叫 ConfigureServices 會彼此附加。Multiple calls to ConfigureServices append to one another. WebHostBuilder 多次呼叫 ConfigureUseStartup 則會取代先前的設定。Multiple calls to Configure or UseStartup on the WebHostBuilder replace previous settings.

主機組態值Host configuration values

WebHostBuilder 依賴下列方法來設定主機組態值:WebHostBuilder relies on the following approaches to set the host configuration values:

  • 主機建立器組態,其中包含 ASPNETCORE_{configurationKey} 格式的環境變數。Host builder configuration, which includes environment variables with the format ASPNETCORE_{configurationKey}. 例如,ASPNETCORE_ENVIRONMENTFor example, ASPNETCORE_ENVIRONMENT.
  • UseContentRootUseConfiguration 之類的延伸模組 (請參閱覆寫組態一節)。Extensions such as UseContentRoot and UseConfiguration (see the Override configuration section).
  • UseSetting 和相關聯的索引鍵。UseSetting and the associated key. 使用 UseSetting 設定值時,此值會設定為字串,而不論其類型為何。When setting a value with UseSetting, the value is set as a string regardless of the type.

主機使用設定最後一個值的任何選項。The host uses whichever option sets a value last. 如需詳細資訊,請參閱下一節的覆寫組態For more information, see Override configuration in the next section.

應用程式索引鍵 (名稱)Application Key (Name)

在主機建構期間呼叫 UseStartupConfigure 時,會自動設定 IHostingEnvironment.ApplicationName 屬性。The IHostingEnvironment.ApplicationName property is automatically set when UseStartup or Configure is called during host construction. 該值會設定為包含應用程式進入點的組件名稱。The value is set to the name of the assembly containing the app's entry point. 若要明確設定該值,請使用 WebHostDefaults.ApplicationKeyTo set the value explicitly, use the WebHostDefaults.ApplicationKey:

索引鍵:applicationNameKey: applicationName
類型stringType: string
預設:包含應用程式進入點的組件名稱。Default: The name of the assembly containing the app's entry point.
設定使用UseSettingSet using: UseSetting
環境變數ASPNETCORE_APPLICATIONNAMEEnvironment variable: ASPNETCORE_APPLICATIONNAME

WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.ApplicationKey, "CustomApplicationName")

擷取啟動錯誤Capture Startup Errors

此設定會控制啟動錯誤的擷取。This setting controls the capture of startup errors.

索引鍵:captureStartupErrorsKey: captureStartupErrors
類型bool (true1)Type: bool (true or 1)
預設:預設為 false,除非應用程式執行時在 IIS 背後有 Kestrel,此時預設即為 trueDefault: Defaults to false unless the app runs with Kestrel behind IIS, where the default is true.
設定使用CaptureStartupErrorsSet using: CaptureStartupErrors
環境變數ASPNETCORE_CAPTURESTARTUPERRORSEnvironment variable: ASPNETCORE_CAPTURESTARTUPERRORS

當它為 false 時,啟動期間發生的錯誤會導致主機結束。When false, errors during startup result in the host exiting. 當它為 true 時,主機會擷取啟動期間的例外狀況,並嘗試啟動伺服器。When true, the host captures exceptions during startup and attempts to start the server.

WebHost.CreateDefaultBuilder(args)
    .CaptureStartupErrors(true)

內容根目錄Content Root

此設定可決定 ASP.NET Core 開始搜尋內容檔案 (例如 MVC 檢視) 的位置。This setting determines where ASP.NET Core begins searching for content files, such as MVC views.

索引鍵:contentRootKey: contentRoot
類型stringType: string
預設:預設為應用程式組件所在的資料夾。Default: Defaults to the folder where the app assembly resides.
設定使用UseContentRootSet using: UseContentRoot
環境變數ASPNETCORE_CONTENTROOTEnvironment variable: ASPNETCORE_CONTENTROOT

內容根目錄也作為 Web 根目錄設定的基底路徑。The content root is also used as the base path for the Web Root setting. 如果路徑不存在,就無法啟動主機。If the path doesn't exist, the host fails to start.

WebHost.CreateDefaultBuilder(args)
    .UseContentRoot("c:\\<content-root>")

詳細錯誤Detailed Errors

決定是否應該擷取詳細的錯誤。Determines if detailed errors should be captured.

索引鍵:detailedErrorsKey: detailedErrors
類型bool (true1)Type: bool (true or 1)
預設值:falseDefault: false
設定使用UseSettingSet using: UseSetting
環境變數ASPNETCORE_DETAILEDERRORSEnvironment variable: ASPNETCORE_DETAILEDERRORS

啟用時 (或當 Environment 設定為 Development 時),應用程式會擷取詳細例外狀況。When enabled (or when the Environment is set to Development), the app captures detailed exceptions.

WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.DetailedErrorsKey, "true")

環境Environment

設定應用程式的環境。Sets the app's environment.

索引鍵:environmentKey: environment
類型stringType: string
預設:生產環境Default: Production
設定使用UseEnvironmentSet using: UseEnvironment
環境變數ASPNETCORE_ENVIRONMENTEnvironment variable: ASPNETCORE_ENVIRONMENT

環境可以設定為任何值。The environment can be set to any value. 架構定義的值包括 DevelopmentStagingProductionFramework-defined values include Development, Staging, and Production. 值不區分大小寫。Values aren't case sensitive. 根據預設,Environment 是從 ASPNETCORE_ENVIRONMENT 環境變數讀取。By default, the Environment is read from the ASPNETCORE_ENVIRONMENT environment variable. 使用 Visual Studio 時,可能會在 launchSettings.json 檔案設定環境變數。When using Visual Studio, environment variables may be set in the launchSettings.json file. 如需詳細資訊,請參閱 在 ASP.NET Core 中使用多個環境For more information, see 在 ASP.NET Core 中使用多個環境.

WebHost.CreateDefaultBuilder(args)
    .UseEnvironment(EnvironmentName.Development)

裝載啟動組件Hosting Startup Assemblies

設定應用程式的裝載啟動組件。Sets the app's hosting startup assemblies.

索引鍵:hostingStartupAssembliesKey: hostingStartupAssemblies
類型stringType: string
預設:空字串Default: Empty string
設定使用UseSettingSet using: UseSetting
環境變數ASPNETCORE_HOSTINGSTARTUPASSEMBLIESEnvironment variable: ASPNETCORE_HOSTINGSTARTUPASSEMBLIES

在啟動時載入的裝載啟動組件字串,以分號分隔。A semicolon-delimited string of hosting startup assemblies to load on startup.

雖然設定值會預設為空字串,但裝載啟動組件一律會包含應用程式的組件。Although the configuration value defaults to an empty string, the hosting startup assemblies always include the app's assembly. 提供裝載啟動組件時,它們會新增至應用程式的組件,以便在應用程式在啟動時建置其通用服務時載入。When hosting startup assemblies are provided, they're added to the app's assembly for loading when the app builds its common services during startup.

WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.HostingStartupAssembliesKey, "assembly1;assembly2")

HTTPS 連接埠HTTPS Port

設定 HTTPS 重新導向連接埠。Set the HTTPS redirect port. 用於強制 HTTPSUsed in enforcing HTTPS.

索引鍵:https_port 類型string 預設:未設定預設值。Key: https_port Type: string Default: A default value isn't set. 設定使用UseSetting 環境變數ASPNETCORE_HTTPS_PORTSet using: UseSetting Environment variable: ASPNETCORE_HTTPS_PORT

WebHost.CreateDefaultBuilder(args)
    .UseSetting("https_port", "8080")

裝載啟動排除組件Hosting Startup Exclude Assemblies

在啟動時排除以分號分隔的裝載啟動組件字串。A semicolon-delimited string of hosting startup assemblies to exclude on startup.

索引鍵:hostingStartupExcludeAssembliesKey: hostingStartupExcludeAssemblies
類型stringType: string
預設:空字串Default: Empty string
設定使用UseSettingSet using: UseSetting
環境變數ASPNETCORE_HOSTINGSTARTUPEXCLUDEASSEMBLIESEnvironment variable: ASPNETCORE_HOSTINGSTARTUPEXCLUDEASSEMBLIES

WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.HostingStartupExcludeAssembliesKey, "assembly1;assembly2")

偏好裝載 URLPrefer Hosting URLs

表示主機是否應接聽使用 WebHostBuilder 設定的 URL,而不是 IServer 實作所設定的 URL。Indicates whether the host should listen on the URLs configured with the WebHostBuilder instead of those configured with the IServer implementation.

索引鍵:preferHostingUrlsKey: preferHostingUrls
類型bool (true1)Type: bool (true or 1)
預設值:trueDefault: true
設定使用PreferHostingUrlsSet using: PreferHostingUrls
環境變數ASPNETCORE_PREFERHOSTINGURLSEnvironment variable: ASPNETCORE_PREFERHOSTINGURLS

WebHost.CreateDefaultBuilder(args)
    .PreferHostingUrls(false)

防止裝載啟動Prevent Hosting Startup

可防止自動載入裝載啟動組件,包括應用程式組件所設定的裝載啟動組件。Prevents the automatic loading of hosting startup assemblies, including hosting startup assemblies configured by the app's assembly. 如需詳細資訊,請參閱 在 ASP.NET Core 中使用裝載啟動組件For more information, see 在 ASP.NET Core 中使用裝載啟動組件.

索引鍵preventHostingStartupKey: preventHostingStartup
類型bool (true1)Type: bool (true or 1)
預設值:falseDefault: false
設定使用UseSettingSet using: UseSetting
環境變數ASPNETCORE_PREVENTHOSTINGSTARTUPEnvironment variable: ASPNETCORE_PREVENTHOSTINGSTARTUP

WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.PreventHostingStartupKey, "true")

伺服器 URLServer URLs

表示伺服器應該接聽要求的 IP 位址或主機位址,以及連接埠和通訊協定。Indicates the IP addresses or host addresses with ports and protocols that the server should listen on for requests.

索引鍵:urlsKey: urls
類型stringType: string
預設值: http://localhost:5000Default: http://localhost:5000
設定使用UseUrlsSet using: UseUrls
環境變數ASPNETCORE_URLSEnvironment variable: ASPNETCORE_URLS

設定為伺服器應該回應的 URL 前置清單,並以分號 (;) 分隔。Set to a semicolon-separated (;) list of URL prefixes to which the server should respond. 例如,http://localhost:123For example, http://localhost:123. 使用 "*",表示伺服器應接聽任何 IP 位址或主機名稱上的要求,並使用指定的連接埠和通訊協定 (例如,http://*:5000)。Use "*" to indicate that the server should listen for requests on any IP address or hostname using the specified port and protocol (for example, http://*:5000). 通訊協定 (http://https://) 必須包含在每個 URL 中。The protocol (http:// or https://) must be included with each URL. 支援的格式會依伺服器而有所不同。Supported formats vary among servers.

WebHost.CreateDefaultBuilder(args)
    .UseUrls("http://*:5000;http://localhost:5001;https://hostname:5002")

Kestrel 有它自己的端點設定 API。Kestrel has its own endpoint configuration API. 如需詳細資訊,請參閱 ASP.NET Core 中的 Kestrel 網頁伺服器實作For more information, see ASP.NET Core 中的 Kestrel 網頁伺服器實作.

關機逾時Shutdown Timeout

指定等待 Web 主機關機的時間長度。Specifies the amount of time to wait for Web Host to shut down.

索引鍵:shutdownTimeoutSecondsKey: shutdownTimeoutSeconds
類型intType: int
預設:5Default: 5
設定使用UseShutdownTimeoutSet using: UseShutdownTimeout
環境變數ASPNETCORE_SHUTDOWNTIMEOUTSECONDSEnvironment variable: ASPNETCORE_SHUTDOWNTIMEOUTSECONDS

雖然索引鍵接受 intUseSetting (例如 .UseSetting(WebHostDefaults.ShutdownTimeoutKey, "10")),UseShutdownTimeout 擴充方法會採用 TimeSpanAlthough the key accepts an int with UseSetting (for example, .UseSetting(WebHostDefaults.ShutdownTimeoutKey, "10")), the UseShutdownTimeout extension method takes a TimeSpan.

在逾時期間,裝載會:During the timeout period, hosting:

如果在所有的託管服務停止之前逾時期限已到期,則應用程式關閉時,會停止任何剩餘的作用中服務。If the timeout period expires before all of the hosted services stop, any remaining active services are stopped when the app shuts down. 即使服務尚未完成處理也會停止。The services stop even if they haven't finished processing. 如果服務需要更多時間才能停止,請增加逾時。If services require additional time to stop, increase the timeout.

WebHost.CreateDefaultBuilder(args)
    .UseShutdownTimeout(TimeSpan.FromSeconds(10))

啟動組件Startup Assembly

決定要搜尋 Startup 類別的組件。Determines the assembly to search for the Startup class.

索引鍵:startupAssemblyKey: startupAssembly
類型stringType: string
預設:應用程式的組件Default: The app's assembly
設定使用UseStartupSet using: UseStartup
環境變數ASPNETCORE_STARTUPASSEMBLYEnvironment variable: ASPNETCORE_STARTUPASSEMBLY

可以參考依名稱 (string) 或類型 (TStartup) 的組件。The assembly by name (string) or type (TStartup) can be referenced. 如果呼叫多個 UseStartup 方法,最後一個將會優先。If multiple UseStartup methods are called, the last one takes precedence.

WebHost.CreateDefaultBuilder(args)
    .UseStartup("StartupAssemblyName")
WebHost.CreateDefaultBuilder(args)
    .UseStartup<TStartup>()

Web 根目錄Web Root

設定應用程式靜態資產的相對路徑。Sets the relative path to the app's static assets.

索引鍵:webrootKey: webroot
類型stringType: string
預設:如果未指定,則預設為 "(Content Root)/wwwroot" (若該路徑存在的話)。Default: If not specified, the default is "(Content Root)/wwwroot", if the path exists. 如果路徑不存在,則會使用無作業檔案提供者。If the path doesn't exist, then a no-op file provider is used.
設定使用UseWebRootSet using: UseWebRoot
環境變數ASPNETCORE_WEBROOTEnvironment variable: ASPNETCORE_WEBROOT

WebHost.CreateDefaultBuilder(args)
    .UseWebRoot("public")

覆寫組態Override configuration

使用 Configuration 來設定 Web 主機。Use Configuration to configure Web Host. 在下列範例中,主機組態選擇性指定於 hostsettings.json 檔案中。In the following example, host configuration is optionally specified in a hostsettings.json file. hostsettings.json 檔案載入的任何組態,可以用命令列引數加以覆寫。Any configuration loaded from the hostsettings.json file may be overridden by command-line arguments. 建置的組態 (在 config 中) 用以使用 UseConfiguration 來設定主機。The built configuration (in config) is used to configure the host with UseConfiguration. IWebHostBuilder 設定會新增到應用程式的組態,但反之則不然 —ConfigureAppConfiguration 並不會影響 IWebHostBuilder 組態。IWebHostBuilder configuration is added to the app's configuration, but the converse isn't true—ConfigureAppConfiguration doesn't affect the IWebHostBuilder configuration.

首先使用 hostsettings.json 組態來覆寫 UseUrls 所提供的組態,其次是命令列引數組態:Overriding the configuration provided by UseUrls with hostsettings.json config first, command-line argument config second:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("hostsettings.json", optional: true)
            .AddCommandLine(args)
            .Build();

        return WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://*:5000")
            .UseConfiguration(config)
            .Configure(app =>
            {
                app.Run(context => 
                    context.Response.WriteAsync("Hello, World!"));
            });
    }
}

hostsettings.jsonhostsettings.json:

{
    urls: "http://*:5005"
}

注意

UseConfiguration 擴充方法目前無法剖析 GetSection 傳回的組態區段 (例如 .UseConfiguration(Configuration.GetSection("section"))The UseConfiguration extension method isn't currently capable of parsing a configuration section returned by GetSection (for example, .UseConfiguration(Configuration.GetSection("section")). GetSection 方法會將設定索引鍵篩選到要求的區段,但保留索引鍵上的區段名稱 (例如 section:urlssection:environment)。The GetSection method filters the configuration keys to the section requested but leaves the section name on the keys (for example, section:urls, section:environment). UseConfiguration 方法預期索引鍵要符合 WebHostBuilder 索引鍵 (例如 urlsenvironment)。The UseConfiguration method expects the keys to match the WebHostBuilder keys (for example, urls, environment). 索引鍵上的區段名稱存在可避免區段的值設定主機。The presence of the section name on the keys prevents the section's values from configuring the host. 這個問題將在近期的版本中解決。This issue will be addressed in an upcoming release. 如需詳細資訊和因應措施,請參閱 Passing configuration section into WebHostBuilder.UseConfiguration uses full keys (將設定區段傳遞到 WebHostBuilder.UseConfiguration 會使用完整索引鍵)。For more information and workarounds, see Passing configuration section into WebHostBuilder.UseConfiguration uses full keys.

UseConfiguration 只會將索引鍵從提供的 IConfiguration 複製到主機建立器的組態。UseConfiguration only copies keys from the provided IConfiguration to the host builder configuration. 因此,為 JSON、INI 和 XML 設定檔設定 reloadOnChange: true 沒有任何作用。Therefore, setting reloadOnChange: true for JSON, INI, and XML settings files has no effect.

若要指定主機在特定 URL 上執行,所要的值可以在執行 dotnet run 時從命令提示字元傳入。To specify the host run on a particular URL, the desired value can be passed in from a command prompt when executing dotnet run. 命令列引數會覆寫 hostsettings.json 檔案的 urls 值,且伺服器會接聽連接埠 8080:The command-line argument overrides the urls value from the hostsettings.json file, and the server listens on port 8080:

dotnet run --urls "http://*:8080"

管理主機Manage the host

執行Run

Run 方法會啟動 Web 應用程式,並且封鎖呼叫執行緒,直到主機關閉為止:The Run method starts the web app and blocks the calling thread until the host is shut down:

host.Run();

啟動Start

藉由呼叫 Start 方法,以非封鎖方式執行主機:Run the host in a non-blocking manner by calling its Start method:

using (host)
{
    host.Start();
    Console.ReadLine();
}

如果 URL 的清單傳遞至 Start 方法,它會接聽指定的 URL:If a list of URLs is passed to the Start method, it listens on the URLs specified:

var urls = new List<string>()
{
    "http://*:5000",
    "http://localhost:5001"
};

var host = new WebHostBuilder()
    .UseKestrel()
    .UseStartup<Startup>()
    .Start(urls.ToArray());

using (host)
{
    Console.ReadLine();
}

應用程式可以使用預先設定的 CreateDefaultBuilder 預設值,使用便利的靜態方法初始化並啟動新的主機。The app can initialize and start a new host using the pre-configured defaults of CreateDefaultBuilder using a static convenience method. 這些方法會啟動伺服器而無主控台輸出,且在使用 WaitForShutdown 時等候中斷 (Ctrl-C/SIGINT 或 SIGTERM):These methods start the server without console output and with WaitForShutdown wait for a break (Ctrl-C/SIGINT or SIGTERM):

Start(RequestDelegate app)Start(RequestDelegate app)

使用 RequestDelegate 啟動:Start with a RequestDelegate:

using (var host = WebHost.Start(app => app.Response.WriteAsync("Hello, World!")))
{
    Console.WriteLine("Use Ctrl-C to shutdown the host...");
    host.WaitForShutdown();
}

在瀏覽器中提出要求給 http://localhost:5000,以收到 "Hello World!" 回應Make a request in the browser to http://localhost:5000 to receive the response "Hello World!" WaitForShutdown 會封鎖,直到發出中斷 (Ctrl-C/SIGINT 或 SIGTERM)。WaitForShutdown blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. 應用程式會顯示 Console.WriteLine 訊息並等候按鍵動作以便結束。The app displays the Console.WriteLine message and waits for a keypress to exit.

Start(string url, RequestDelegate app)Start(string url, RequestDelegate app)

使用 URL 和 RequestDelegate 來啟動:Start with a URL and RequestDelegate:

using (var host = WebHost.Start("http://localhost:8080", app => app.Response.WriteAsync("Hello, World!")))
{
    Console.WriteLine("Use Ctrl-C to shutdown the host...");
    host.WaitForShutdown();
}

產生與 Start(RequestDelegate app) 相同的結果,除了應用程式會在 http://localhost:8080 回應。Produces the same result as Start(RequestDelegate app), except the app responds on http://localhost:8080.

Start(Action<IRouteBuilder> routeBuilder)Start(Action<IRouteBuilder> routeBuilder)

使用 IRouteBuilder (Microsoft.AspNetCore.Routing) 的執行個體來使用路由中介軟體:Use an instance of IRouteBuilder (Microsoft.AspNetCore.Routing) to use routing middleware:

using (var host = WebHost.Start(router => router
    .MapGet("hello/{name}", (req, res, data) => 
        res.WriteAsync($"Hello, {data.Values["name"]}!"))
    .MapGet("buenosdias/{name}", (req, res, data) => 
        res.WriteAsync($"Buenos dias, {data.Values["name"]}!"))
    .MapGet("throw/{message?}", (req, res, data) => 
        throw new Exception((string)data.Values["message"] ?? "Uh oh!"))
    .MapGet("{greeting}/{name}", (req, res, data) => 
        res.WriteAsync($"{data.Values["greeting"]}, {data.Values["name"]}!"))
    .MapGet("", (req, res, data) => res.WriteAsync("Hello, World!"))))
{
    Console.WriteLine("Use Ctrl-C to shutdown the host...");
    host.WaitForShutdown();
}

使用下列瀏覽器要求與範例:Use the following browser requests with the example:

要求Request 回應Response
http://localhost:5000/hello/Martin Hello, Martin!Hello, Martin!
http://localhost:5000/buenosdias/Catrina Buenos dias, Catrina!Buenos dias, Catrina!
http://localhost:5000/throw/ooops! 擲回例外狀況,字串為 "ooops!"Throws an exception with string "ooops!"
http://localhost:5000/throw 擲回例外狀況,字串為 "Un oh!"Throws an exception with string "Uh oh!"
http://localhost:5000/Sante/Kevin Sante, Kevin!Sante, Kevin!
http://localhost:5000 Hello World!Hello World!

WaitForShutdown 會封鎖,直到發出中斷 (Ctrl-C/SIGINT 或 SIGTERM)。WaitForShutdown blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. 應用程式會顯示 Console.WriteLine 訊息並等候按鍵動作以便結束。The app displays the Console.WriteLine message and waits for a keypress to exit.

Start(string url, Action<IRouteBuilder> routeBuilder)Start(string url, Action<IRouteBuilder> routeBuilder)

使用 URL 和 IRouteBuilder 的執行個體:Use a URL and an instance of IRouteBuilder:

using (var host = WebHost.Start("http://localhost:8080", router => router
    .MapGet("hello/{name}", (req, res, data) => 
        res.WriteAsync($"Hello, {data.Values["name"]}!"))
    .MapGet("buenosdias/{name}", (req, res, data) => 
        res.WriteAsync($"Buenos dias, {data.Values["name"]}!"))
    .MapGet("throw/{message?}", (req, res, data) => 
        throw new Exception((string)data.Values["message"] ?? "Uh oh!"))
    .MapGet("{greeting}/{name}", (req, res, data) => 
        res.WriteAsync($"{data.Values["greeting"]}, {data.Values["name"]}!"))
    .MapGet("", (req, res, data) => res.WriteAsync("Hello, World!"))))
{
    Console.WriteLine("Use Ctrl-C to shut down the host...");
    host.WaitForShutdown();
}

產生與 Start(Action<IRouteBuilder> routeBuilder) 相同的結果,除了應用程式會在 http://localhost:8080 回應。Produces the same result as Start(Action<IRouteBuilder> routeBuilder), except the app responds at http://localhost:8080.

StartWith(Action<IApplicationBuilder> app)StartWith(Action<IApplicationBuilder> app)

提供委派以設定 IApplicationBuilderProvide a delegate to configure an IApplicationBuilder:

using (var host = WebHost.StartWith(app => 
    app.Use(next => 
    {
        return async context => 
        {
            await context.Response.WriteAsync("Hello World!");
        };
    })))
{
    Console.WriteLine("Use Ctrl-C to shut down the host...");
    host.WaitForShutdown();
}

在瀏覽器中提出要求給 http://localhost:5000,以收到 "Hello World!" 回應Make a request in the browser to http://localhost:5000 to receive the response "Hello World!" WaitForShutdown 會封鎖,直到發出中斷 (Ctrl-C/SIGINT 或 SIGTERM)。WaitForShutdown blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. 應用程式會顯示 Console.WriteLine 訊息並等候按鍵動作以便結束。The app displays the Console.WriteLine message and waits for a keypress to exit.

StartWith(string url, Action<IApplicationBuilder> app)StartWith(string url, Action<IApplicationBuilder> app)

提供 URL 和委派以設定 IApplicationBuilderProvide a URL and a delegate to configure an IApplicationBuilder:

using (var host = WebHost.StartWith("http://localhost:8080", app => 
    app.Use(next => 
    {
        return async context => 
        {
            await context.Response.WriteAsync("Hello World!");
        };
    })))
{
    Console.WriteLine("Use Ctrl-C to shut down the host...");
    host.WaitForShutdown();
}

產生與 StartWith(Action<IApplicationBuilder> app) 相同的結果,除了應用程式會在 http://localhost:8080 回應。Produces the same result as StartWith(Action<IApplicationBuilder> app), except the app responds on http://localhost:8080.

IHostingEnvironment 介面IHostingEnvironment interface

IHostingEnvironment 介面提供應用程式的 Web 裝載環境相關資訊。The IHostingEnvironment interface provides information about the app's web hosting environment. 使用建構函式插入以取得 IHostingEnvironment,才能使用其屬性和擴充方法:Use constructor injection to obtain the IHostingEnvironment in order to use its properties and extension methods:

public class CustomFileReader
{
    private readonly IHostingEnvironment _env;

    public CustomFileReader(IHostingEnvironment env)
    {
        _env = env;
    }

    public string ReadFile(string filePath)
    {
        var fileProvider = _env.WebRootFileProvider;
        // Process the file here
    }
}

以慣例為基礎的方法可用來根據環境在啟動時設定應用程式。A convention-based approach can be used to configure the app at startup based on the environment. 或者,將 IHostingEnvironment 插入至 Startup 建構函式,以便用於 ConfigureServicesAlternatively, inject the IHostingEnvironment into the Startup constructor for use in ConfigureServices:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        HostingEnvironment = env;
    }

    public IHostingEnvironment HostingEnvironment { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        if (HostingEnvironment.IsDevelopment())
        {
            // Development configuration
        }
        else
        {
            // Staging/Production configuration
        }

        var contentRootPath = HostingEnvironment.ContentRootPath;
    }
}

注意

除了 IsDevelopment 擴充方法,IHostingEnvironment 也提供 IsStagingIsProductionIsEnvironment(string environmentName) 方法。In addition to the IsDevelopment extension method, IHostingEnvironment offers IsStaging, IsProduction, and IsEnvironment(string environmentName) methods. 如需詳細資訊,請參閱 在 ASP.NET Core 中使用多個環境For more information, see 在 ASP.NET Core 中使用多個環境.

IHostingEnvironment 服務也可直接插入至 Configure 方法,以便設定處理管線:The IHostingEnvironment service can also be injected directly into the Configure method for setting up the processing pipeline:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        // In Development, use the Developer Exception Page
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // In Staging/Production, route exceptions to /error
        app.UseExceptionHandler("/error");
    }

    var contentRootPath = env.ContentRootPath;
}

建立自訂中介軟體時,IHostingEnvironment 可以插入至 Invoke 方法:IHostingEnvironment can be injected into the Invoke method when creating custom middleware:

public async Task Invoke(HttpContext context, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        // Configure middleware for Development
    }
    else
    {
        // Configure middleware for Staging/Production
    }

    var contentRootPath = env.ContentRootPath;
}

IApplicationLifetime 介面IApplicationLifetime interface

IApplicationLifetime 允許啟動後和關機活動。IApplicationLifetime allows for post-startup and shutdown activities. 在介面上的三個屬性是用來註冊定義啟動和關閉事件之 Action 方法的取消語彙基元。Three properties on the interface are cancellation tokens used to register Action methods that define startup and shutdown events.

取消語彙基元Cancellation Token 觸發時機…Triggered when…
ApplicationStartedApplicationStarted 已完全啟動主機。The host has fully started.
ApplicationStoppedApplicationStopped 主機正在完成正常關機程序。The host is completing a graceful shutdown. 應該處理所有要求。All requests should be processed. 關機封鎖,直到完成此事件。Shutdown blocks until this event completes.
ApplicationStoppingApplicationStopping 主機正在執行正常關機程序。The host is performing a graceful shutdown. 可能仍在處理要求。Requests may still be processing. 關機封鎖,直到完成此事件。Shutdown blocks until this event completes.
public class Startup
{
    public void Configure(IApplicationBuilder app, IApplicationLifetime appLifetime)
    {
        appLifetime.ApplicationStarted.Register(OnStarted);
        appLifetime.ApplicationStopping.Register(OnStopping);
        appLifetime.ApplicationStopped.Register(OnStopped);

        Console.CancelKeyPress += (sender, eventArgs) =>
        {
            appLifetime.StopApplication();
            // Don't terminate the process immediately, wait for the Main thread to exit gracefully.
            eventArgs.Cancel = true;
        };
    }

    private void OnStarted()
    {
        // Perform post-startup activities here
    }

    private void OnStopping()
    {
        // Perform on-stopping activities here
    }

    private void OnStopped()
    {
        // Perform post-stopped activities here
    }
}

StopApplication 會要求應用程式終止。StopApplication requests termination of the app. 當呼叫類別的 Shutdown 方法時,下列類別使用 StopApplication 來順利關閉應用程式:The following class uses StopApplication to gracefully shut down an app when the class's Shutdown method is called:

public class MyClass
{
    private readonly IApplicationLifetime _appLifetime;

    public MyClass(IApplicationLifetime appLifetime)
    {
        _appLifetime = appLifetime;
    }

    public void Shutdown()
    {
        _appLifetime.StopApplication();
    }
}

範圍驗證Scope validation

如果應用程式的環境是「開發」,CreateDefaultBuilder 會將 ServiceProviderOptions.ValidateScopes 設定為 trueCreateDefaultBuilder sets ServiceProviderOptions.ValidateScopes to true if the app's environment is Development.

ValidateScopes 設定為 true 時,預設服務提供者會執行檢查以確認:When ValidateScopes is set to true, the default service provider performs checks to verify that:

  • 範圍服務不是直接或間接由根服務提供者解析。Scoped services aren't directly or indirectly resolved from the root service provider.
  • 範圍服務不是直接或間接插入至單一服務。Scoped services aren't directly or indirectly injected into singletons.

根服務提供者會在呼叫 BuildServiceProvider 時建立。The root service provider is created when BuildServiceProvider is called. 當提供者啟動應用程式時,根服務提供者的存留期與應用程式/伺服器的存留期一致,並會在應用程式關閉時處置。The root service provider's lifetime corresponds to the app/server's lifetime when the provider starts with the app and is disposed when the app shuts down.

範圍服務會由建立這些服務的容器處置。Scoped services are disposed by the container that created them. 若是在根容器中建立範圍服務,因為當應用程式/伺服器關機時,服務只會由根容器處理,所以服務的存留期會提升為單一服務等級。If a scoped service is created in the root container, the service's lifetime is effectively promoted to singleton because it's only disposed by the root container when app/server is shut down. 當呼叫 BuildServiceProvider 時,驗證服務範圍會攔截到這些情況。Validating service scopes catches these situations when BuildServiceProvider is called.

若要一律驗證範圍,包括在實際執行環境中,請使用主機產生器上的 UseDefaultServiceProvider 來設定 ServiceProviderOptionsTo always validate scopes, including in the Production environment, configure the ServiceProviderOptions with UseDefaultServiceProvider on the host builder:

WebHost.CreateDefaultBuilder(args)
    .UseDefaultServiceProvider((context, options) => {
        options.ValidateScopes = true;
    })

其他資源Additional resources