.NET Generic Host in ASP.NET Core
.NET Generic Host in ASP.NET Core
The ASP.NET Core templates create a .NET Core Generic Host (HostBuilder).
This topic provides information on using .NET Generic Host in ASP.NET Core. For information on using .NET Generic Host in console apps, see .NET Generic Host.
Host definition
A host is an object that encapsulates an app's resources, such as:
- Dependency injection (DI)
- Logging
- Configuration
IHostedService
implementations
When a host starts, it calls IHostedService.StartAsync on each implementation of IHostedService registered in the service container's collection of hosted services. In a web app, one of the IHostedService
implementations is a web service that starts an HTTP server implementation.
The main reason for including all of the app's interdependent resources in one object is lifetime management: control over app startup and graceful shutdown.
Set up a host
The host is typically configured, built, and run by code in the Program
class. The Main
method:
- Calls a
CreateHostBuilder
method to create and configure a builder object. - Calls
Build
andRun
methods on the builder object.
The ASP.NET Core web templates generate the following code to create a host:
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
The following code creates a non-HTTP workload with an IHostedService
implementation added to the DI container.
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); }); }
For an HTTP workload, the Main
method is the same but CreateHostBuilder
calls ConfigureWebHostDefaults
:
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
If the app uses Entity Framework Core, don't change the name or signature of the CreateHostBuilder
method. The Entity Framework Core tools expect to find a CreateHostBuilder
method that configures the host without running the app. For more information, see Design-time DbContext Creation.
Default builder settings
The CreateDefaultBuilder method:
- Sets the content root to the path returned by GetCurrentDirectory.
- Loads host configuration from:
- Environment variables prefixed with
DOTNET_
. - Command-line arguments.
- Environment variables prefixed with
- Loads app configuration from:
- appsettings.json.
- appsettings.{Environment}.json.
- User secrets when the app runs in the
Development
environment. - Environment variables.
- Command-line arguments.
- Adds the following logging providers:
- Console
- Debug
- EventSource
- EventLog (only when running on Windows)
- Enables scope validation and dependency validation when the environment is Development.
The ConfigureWebHostDefaults method:
- Loads host configuration from environment variables prefixed with
ASPNETCORE_
. - Sets Kestrel server as the web server and configures it using the app's hosting configuration providers. For the Kestrel server's default options, see Configure options for the ASP.NET Core Kestrel web server.
- Adds Host Filtering middleware.
- Adds Forwarded Headers middleware if
ASPNETCORE_FORWARDEDHEADERS_ENABLED
equalstrue
. - Enables IIS integration. For the IIS default options, see Host ASP.NET Core on Windows with IIS.
The Settings for all app types and Settings for web apps sections later in this article show how to override default builder settings.
GenericHostBuilderExtensions.ConfigureWebHostDefaults(IHostBuilder, Action<IWebHostBuilder>) Method
Remarks
The following defaults are applied to the IHostBuilder:
- use Kestrel as the web server and configure it using the application's configuration providers
- configure WebRootFileProvider to include static web assets from projects referenced by the entry assembly during development
- adds the HostFiltering middleware
- adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true,
- enable IIS integration
What is the difference between ConfigureWebHostDefaults and ConfigureWebHost methods?
Via ASP.NET Core source code, ConfigureWebHostDefaults
equals to:
public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action<IWebHostBuilder> configure)
{
return builder.ConfigureWebHost(webHostBuilder =>
{
WebHost.ConfigureWebDefaults(webHostBuilder);
configure(webHostBuilder);
});
}
It just calls the ConfigureWebHost
, but will an additional step: ConfigureWebDefaults
.
As for ConfigureWebDefaults
, the source code is pretty long and placed here:
For the difference, ConfigureWebHostDefaults
configures a web host with:
- Use Kestrel as the web server and configure it using the application's configuration providers
- Adds the HostFiltering middleware,
- Adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true,
- Enable IIS integration.
Also, the official document mentioned that:
The ConfigureWebHostDefaults method loads host configuration from environment variables prefixed with "ASPNETCORE_". Sets Kestrel server as the web server and configures it using the app's hosting configuration providers. For the Kestrel server's default options, see Kestrel web server implementation in ASP.NET Core. Adds Host Filtering middleware. Adds Forwarded Headers middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true. Enables IIS integration. For the IIS default options, see Host ASP.NET Core on Windows with IIS.
Document link: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.0#default-builder-settings
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2019-02-25 283. Move Zeroes
2019-02-25 DataContract with Json.Net
2019-02-25 Todo list
2019-02-25 Execution Order for the ApiController
2019-02-25 ASP.NET WEB API 2: HTTP MESSAGE LIFECYLE
2019-02-25 autofac 在webapi中拿到当前request的scope
2019-02-25 234. Palindrome Linked List