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.

对于本主题的 1.1 版本,请下载 ASP.NET Core Web 主机(版本 1.1,PDF)For the 1.1 version of this topic, download ASP.NET Core Web Host (version 1.1, PDF).

本文介绍了 ASP.NET Core Web 主机 (IWebHostBuilder),该主机用于托管 Web 应用。This article covers the ASP.NET Core Web Host (IWebHostBuilder), which is for hosting web apps. 有关 .NET 泛型主机 (IHostBuilder) 的信息,请参阅 .NET 通用主机For information about the .NET Generic Host (IHostBuilder), see .NET 通用主机.

本文介绍了 ASP.NET Core Web 主机 (IWebHostBuilder)。This article covers the ASP.NET Core Web Host (IWebHostBuilder). 在 ASP.NET Core 3.0 中,泛型主机替代了 Web 主机。In ASP.NET Core 3.0, Generic Host replaces Web Host. 有关详细信息,请参阅主机For more information, see The 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. 生成器方法名称 CreateWebHostBuilder 是向外部组件(如实体框架)标识生成器方法的特殊名称。The builder method name, CreateWebHostBuilder, is special name that identifies the builder method to external components, such as Entity Framework.

在项目模板中,Main 位于 Program.cs。In 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 执行下列任务:CreateDefaultBuilder performs the following tasks:

ConfigureAppConfigurationConfigureLogging 以及 IWebHostBuilder 的其他方法和扩展方法可重写和增强 CreateDefaultBuilder 定义的配置。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 在 appsettings.Development.json 和 appsettings.Production.json 中配置的设置,分别为 LogLevel.DebugLogLevel.ErrorThis 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 时建立的 30,000,000 字节默认 Limits.MaxRequestBodySizeThe 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 时建立的 30,000,000 字节默认 Limits.MaxRequestBodySizeThe 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 new 模板中使用的默认值。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 方法的替代方法,从 WebHostBuilder 创建主机是一种受 ASP.NET Core 2.x 支持的方法。As an alternative to using the static CreateDefaultBuilder method, creating a host from WebHostBuilder is a supported approach with ASP.NET Core 2.x. 有关详细信息,请参阅 ASP.NET Core 1.x 选项卡。For more information, see the ASP.NET Core 1.x tab.

设置主机时,可以提供配置ConfigureServices 方法。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
类型:布尔型(true1Type: bool (true or 1)
默认值:默认为 false,除非应用使用 Kestrel 在 IIS 后方运行,其中默认值是 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
类型:布尔型(true1Type: bool (true or 1)
默认值:falseDefault: false
设置使用UseSettingSet using: UseSetting
环境变量ASPNETCORE_DETAILEDERRORSEnvironment variable: ASPNETCORE_DETAILEDERRORS

启用(或当环境设置为 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.

:环境Key: environment
类型:stringType: string
默认值:生产Default: Production
设置使用UseEnvironmentSet using: UseEnvironment
环境变量ASPNETCORE_ENVIRONMENTEnvironment variable: ASPNETCORE_ENVIRONMENT

环境可以设置为任何值。The environment can be set to any value. 框架定义的值包括 Development``StagingProductionFramework-defined values include Development, Staging, and Production. 值不区分大小写。Values aren't case sensitive. 默认情况下,从 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;类型:字符串; 默认值:未设置默认值。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
类型:布尔型(true1Type: 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
类型:布尔型(true1Type: 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. 使用“*”指示服务器应针对请求侦听的使用特定端口和协议(例如 http://*:5000)的 IP 地址或主机名。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 Web 服务器实现For more information, see ASP.NET Core 中的 Kestrel Web 服务器实现.

关闭超时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

虽然键使用 UseSetting 接受 int(例如 .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

使用配置可以配置 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 config 重写 UseUrls 提供的配置,再用命令行参数 config: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.json:hostsettings.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. 有关详细信息和解决方法,请参阅将配置节传入到 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 运行时从命令提示符传入。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();

StartStart

通过调用 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 消息并等待 keypress 退出。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 使用“Uh 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 消息并等待 keypress 退出。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 消息并等待 keypress 退出。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

如果应用环境为“开发”,则 CreateDefaultBuilderServiceProviderOptions.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