ASP.NET Core Web 主机ASP.NET Core Web Host
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.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
的代码位于名为 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. 如果使用 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. 一种替代方法是实现 IDesignTimeDbContextFactory
。An alternative is to implement IDesignTimeDbContextFactory
. 有关详细信息,请参阅设计时 DbContext 创建。For more information, see Design-time DbContext Creation.
CreateDefaultBuilder
执行下列任务:CreateDefaultBuilder
performs the following tasks:
- 使用应用的托管配置提供程序将 Kestrel 服务器配置为 Web 服务器。Configures Kestrel server as the web server using the app's hosting configuration providers. 有关 Kestrel 服务器默认选项,请参阅 ASP.NET Core 中的 Kestrel Web 服务器实现。For the Kestrel server's default options, see ASP.NET Core 中的 Kestrel Web 服务器实现.
- 将内容根目录设置为由 Directory.GetCurrentDirectory 返回的路径。Sets the content root to the path returned by Directory.GetCurrentDirectory.
- 通过以下对象加载主机配置:Loads host configuration from:
- 前缀为
ASPNETCORE_
的环境变量(例如,ASPNETCORE_ENVIRONMENT
)。Environment variables prefixed withASPNETCORE_
(for example,ASPNETCORE_ENVIRONMENT
). - 命令行参数。Command-line arguments.
- 前缀为
- 按以下顺序加载应用配置:Loads app configuration in the following order from:
- appsettings.json.appsettings.json.
- appsettings.{Environment}.json。appsettings.{Environment}.json.
- 应用在使用入口程序集的
Development
环境中运行时的用户机密。User secrets when the app runs in theDevelopment
environment using the entry assembly. - 环境变量。Environment variables.
- 命令行参数。Command-line arguments.
- 配置控制台和调试输出的日志记录。Configures logging for console and debug output. 日志记录包含 appsettings.json 或 appsettings.{Environment}.json 文件的日志记录配置部分中指定的日志筛选规则。Logging includes log filtering rules specified in a Logging configuration section of an appsettings.json or appsettings.{Environment}.json file.
- 使用 ASP.NET Core 模块在 IIS 后面运行时,
CreateDefaultBuilder
会启用 IIS 集成,这会配置应用的基址和端口。When running behind IIS with the ASP.NET Core Module,CreateDefaultBuilder
enables IIS Integration, which configures the app's base address and port. IIS 集成还配置应用以捕获启动错误。IIS Integration also configures the app to capture startup errors. 有关 IIS 默认选项,请参阅 使用 IIS 在 Windows 上托管 ASP.NET Core。For the IIS default options, see 使用 IIS 在 Windows 上托管 ASP.NET Core. - 如果应用环境为“开发”,请将 ServiceProviderOptions.ValidateScopes 设为
true
。Sets ServiceProviderOptions.ValidateScopes totrue
if the app's environment is Development. 有关详细信息,请参阅作用域验证。For more information, see Scope validation.
ConfigureAppConfiguration、ConfigureLogging 以及 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 用于指定应用的其他
IConfiguration
。ConfigureAppConfiguration is used to specify additionalIConfiguration
for the app. 下面的ConfigureAppConfiguration
调用添加委托,以在 appsettings.xml 文件中添加应用配置。The followingConfigureAppConfiguration
call adds a delegate to include app configuration in the appsettings.xml file. 可多次调用ConfigureAppConfiguration
。ConfigureAppConfiguration
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.Warning。The followingConfigureLogging
call adds a delegate to configure the minimum logging level (SetMinimumLevel) to LogLevel.Warning. 此设置重写CreateDefaultBuilder
在 appsettings.Development.json 和 appsettings.Production.json 中配置的设置,分别为LogLevel.Debug
和LogLevel.Error
。This setting overrides the settings in appsettings.Development.json (LogLevel.Debug
) and appsettings.Production.json (LogLevel.Error
) configured byCreateDefaultBuilder
. 可多次调用ConfigureLogging
。ConfigureLogging
may be called multiple times.WebHost.CreateDefaultBuilder(args) .ConfigureLogging(logging => { logging.SetMinimumLevel(LogLevel.Warning); }) ...
下面调用
ConfigureKestrel
来重写CreateDefaultBuilder
在配置 Kestrel 时建立的 30,000,000 字节默认 Limits.MaxRequestBodySize:The following call toConfigureKestrel
overrides the default Limits.MaxRequestBodySize of 30,000,000 bytes established when Kestrel was configured byCreateDefaultBuilder
:WebHost.CreateDefaultBuilder(args) .ConfigureKestrel((context, options) => { options.Limits.MaxRequestBodySize = 20000000; });
下面调用 UseKestrel 来重写
CreateDefaultBuilder
在配置 Kestrel 时建立的 30,000,000 字节默认 Limits.MaxRequestBodySize:The following call to UseKestrel overrides the default Limits.MaxRequestBodySize of 30,000,000 bytes established when Kestrel was configured byCreateDefaultBuilder
: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 Studio 和 dotnet 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.
设置主机时,可以提供配置和 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
上的 Configure
或 UseStartup
将替换以前的设置。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 formatASPNETCORE_{configurationKey}
. 例如ASPNETCORE_ENVIRONMENT
。For example,ASPNETCORE_ENVIRONMENT
. - UseContentRoot 和 UseConfiguration 等扩展(请参阅重写配置部分)。Extensions such as UseContentRoot and UseConfiguration (see the Override configuration section).
- UseSetting 和关联键。UseSetting and the associated key. 使用
UseSetting
设置值时,该值设置为无论何种类型的字符串。When setting a value withUseSetting
, 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)
在主机构造期间调用 UseStartup 或 Configure 时,会自动设置 IWebHostEnvironment.ApplicationName
属性。The IWebHostEnvironment.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.ApplicationKey:To set the value explicitly, use the WebHostDefaults.ApplicationKey:
在主机构造期间调用 UseStartup 或 Configure 时,会自动设置 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.ApplicationKey:To set the value explicitly, use the WebHostDefaults.ApplicationKey:
密钥:applicationNameKey: applicationName
类型:stringType: string
默认值:包含应用入口点的程序集的名称。Default: The name of the assembly containing the app's entry point.
设置使用:UseSetting
Set using: UseSetting
环境变量:ASPNETCORE_APPLICATIONNAME
Environment variable: ASPNETCORE_APPLICATIONNAME
WebHost.CreateDefaultBuilder(args)
.UseSetting(WebHostDefaults.ApplicationKey, "CustomApplicationName")
捕获启动错误Capture Startup Errors
此设置控制启动错误的捕获。This setting controls the capture of startup errors.
键:captureStartupErrorsKey: captureStartupErrors
类型:布尔型(true
或 1
)Type: bool (true
or 1
)
默认:默认为 false
,除非应用使用 Kestrel 在 IIS 后方运行,其中默认值是 true
。Default: Defaults to false
unless the app runs with Kestrel behind IIS, where the default is true
.
设置使用:CaptureStartupErrors
Set using: CaptureStartupErrors
环境变量:ASPNETCORE_CAPTURESTARTUPERRORS
Environment 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 开始搜索内容文件。This setting determines where ASP.NET Core begins searching for content files.
键:contentRootKey: contentRoot
类型:stringType: string
默认:默认为应用程序集所在的文件夹。Default: Defaults to the folder where the app assembly resides.
设置使用:UseContentRoot
Set using: UseContentRoot
环境变量:ASPNETCORE_CONTENTROOT
Environment variable: ASPNETCORE_CONTENTROOT
内容根目录也用作 Web 根目录的基路径。The content root is also used as the base path for the web root. 如果内容根路径不存在,主机将无法启动。If the content root path doesn't exist, the host fails to start.
WebHost.CreateDefaultBuilder(args)
.UseContentRoot("c:\\<content-root>")
有关详情,请参阅:For more information, see:
详细错误Detailed Errors
确定是否应捕获详细错误。Determines if detailed errors should be captured.
键:detailedErrorsKey: detailedErrors
类型:布尔型(true
或 1
)Type: bool (true
or 1
)
默认值:falseDefault: false
设置使用:UseSetting
Set using: UseSetting
环境变量:ASPNETCORE_DETAILEDERRORS
Environment 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
设置使用:UseEnvironment
Set using: UseEnvironment
环境变量:ASPNETCORE_ENVIRONMENT
Environment variable: ASPNETCORE_ENVIRONMENT
可将环境设置为任何值。The environment can be set to any value. 框架定义的值包括 Development``Staging
和 Production
。Framework-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
设置使用:UseSetting
Set using: UseSetting
环境变量:ASPNETCORE_HOSTINGSTARTUPASSEMBLIES
Environment 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. 用于强制实施 HTTPS。Used in enforcing HTTPS.
键:https_port;类型:字符串;
默认值 :未设置默认值。Key: https_port Type: string
Default: A default value isn't set.
设置使用:UseSetting
环境变量:ASPNETCORE_HTTPS_PORT
Set 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
设置使用:UseSetting
Set using: UseSetting
环境变量:ASPNETCORE_HOSTINGSTARTUPEXCLUDEASSEMBLIES
Environment 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
类型:布尔型(true
或 1
)Type: bool (true
or 1
)
默认值:trueDefault: true
设置使用:PreferHostingUrls
Set using: PreferHostingUrls
环境变量:ASPNETCORE_PREFERHOSTINGURLS
Environment 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
类型:布尔型(true
或 1
)Type: bool (true
or 1
)
默认值:falseDefault: false
设置使用:UseSetting
Set using: UseSetting
环境变量:ASPNETCORE_PREVENTHOSTINGSTARTUP
Environment 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
设置使用:UseUrls
Set using: UseUrls
环境变量:ASPNETCORE_URLS
Environment variable: ASPNETCORE_URLS
设置为服务器应响应的以分号分隔 (;) 的 URL 前缀列表。Set to a semicolon-separated (;) list of URL prefixes to which the server should respond. 例如 http://localhost:123
。For 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
设置使用:UseShutdownTimeout
Set using: UseShutdownTimeout
环境变量:ASPNETCORE_SHUTDOWNTIMEOUTSECONDS
Environment variable: ASPNETCORE_SHUTDOWNTIMEOUTSECONDS
虽然键使用 UseSetting
接受 int(例如 .UseSetting(WebHostDefaults.ShutdownTimeoutKey, "10")
),但是 UseShutdownTimeout 扩展方法采用 TimeSpan。Although 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:
- 触发器 IApplicationLifetime.ApplicationStopping。Triggers IApplicationLifetime.ApplicationStopping.
- 尝试停止托管服务,对服务停止失败的任何错误进行日志记录。Attempts to stop hosted services, logging any errors for services that fail to stop.
如果在所有托管服务停止之前就达到了超时时间,则会在应用关闭时会终止剩余的所有活动的服务。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
设置使用:UseStartup
Set using: UseStartup
环境变量:ASPNETCORE_STARTUPASSEMBLY
Environment 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
默认:默认值为 wwwroot
。Default: The default is wwwroot
. {content root}/wwwroot 的路径必须存在。The path to {content root}/wwwroot must exist. 如果该路径不存在,则使用无操作文件提供程序。If the path doesn't exist, a no-op file provider is used.
设置使用:UseWebRoot
Set using: UseWebRoot
环境变量:ASPNETCORE_WEBROOT
Environment variable: ASPNETCORE_WEBROOT
WebHost.CreateDefaultBuilder(args)
.UseWebRoot("public")
有关详情,请参阅:For more information, see:
重写配置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 只将所提供的 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)
提供委托以配置 IApplicationBuilder
:Provide 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 和委托以配置 IApplicationBuilder
:Provide 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
.
IWebHostEnvironment 接口IWebHostEnvironment interface
IWebHostEnvironment
接口提供有关应用的 Web 托管环境的信息。The IWebHostEnvironment
interface provides information about the app's web hosting environment. 使用构造函数注入获取 IWebHostEnvironment
以使用其属性和扩展方法:Use constructor injection to obtain the IWebHostEnvironment
in order to use its properties and extension methods:
public class CustomFileReader
{
private readonly IWebHostEnvironment _env;
public CustomFileReader(IWebHostEnvironment 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. 或者,将 IWebHostEnvironment
注入到 Startup
构造函数用于 ConfigureServices
:Alternatively, inject the IWebHostEnvironment
into the Startup
constructor for use in ConfigureServices
:
public class Startup
{
public Startup(IWebHostEnvironment env)
{
HostingEnvironment = env;
}
public IWebHostEnvironment HostingEnvironment { get; }
public void ConfigureServices(IServiceCollection services)
{
if (HostingEnvironment.IsDevelopment())
{
// Development configuration
}
else
{
// Staging/Production configuration
}
var contentRootPath = HostingEnvironment.ContentRootPath;
}
}
备注
除了 IsDevelopment
扩展方法,IWebHostEnvironment
提供 IsStaging
、IsProduction
和 IsEnvironment(string environmentName)
方法。In addition to the IsDevelopment
extension method, IWebHostEnvironment
offers IsStaging
, IsProduction
, and IsEnvironment(string environmentName)
methods. 有关详细信息,请参阅 在 ASP.NET Core 中使用多个环境。For more information, see 在 ASP.NET Core 中使用多个环境.
IWebHostEnvironment
服务还可以直接注入到 Configure
方法以设置处理管道:The IWebHostEnvironment
service can also be injected directly into the Configure
method for setting up the processing pipeline:
public void Configure(IApplicationBuilder app, IWebHostEnvironment 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;
}
创建自定义中间件时可以将 IWebHostEnvironment
注入 Invoke
方法:IWebHostEnvironment
can be injected into the Invoke
method when creating custom middleware:
public async Task Invoke(HttpContext context, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
// Configure middleware for Development
}
else
{
// Configure middleware for Staging/Production
}
var contentRootPath = env.ContentRootPath;
}
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
构造函数用于 ConfigureServices
:Alternatively, 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
提供 IsStaging
、IsProduction
和 IsEnvironment(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;
}
IHostApplicationLifetime 接口IHostApplicationLifetime interface
IHostApplicationLifetime
允许后启动和关闭活动。IHostApplicationLifetime
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… |
---|---|
ApplicationStarted |
主机已完全启动。The host has fully started. |
ApplicationStopped |
主机正在完成正常关闭。The host is completing a graceful shutdown. 应处理所有请求。All requests should be processed. 关闭受到阻止,直到完成此事件。Shutdown blocks until this event completes. |
ApplicationStopping |
主机正在执行正常关闭。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, IHostApplicationLifetime 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 IHostApplicationLifetime _appLifetime;
public MyClass(IHostApplicationLifetime appLifetime)
{
_appLifetime = appLifetime;
}
public void Shutdown()
{
_appLifetime.StopApplication();
}
}
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 设为 true
。CreateDefaultBuilder 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 配置 ServiceProviderOptions:To 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;
})