I see 2 nearly the same extension methods on generic host builder class (HostBuilder
): ConfigureWebHostDefaults
and ConfigureWebHost
. They have the same signature and locate in different assemblies. I saw ConfigureWebHostDefaults
in guides but there is nearly nothing about ConfigureWebHost
. What is the difference between them?
ConfigureWebHostDefaults(IHostBuilder, Action<IWebHostBuilder>) Configures a IHostBuilder with defaults for hosting a web app. This should be called before application specific configuration to avoid it overwriting provided services, configuration sources, environments, content root, etc.
IHostBuilder : The host builder constructs the host and configures various services. This is the generalization of the previous IWebHostBuilder but also basically does the same just for generic IHost . It configures the host before the application starts. There is the Host.
There is one main difference to be aware of and that is HostBuilder doesn't provide an extension method that allows you to use a startup class as we can with the WebHostBuilder. This decision was made primarily to avoid the need to create two separate DI containers behind the scenes.
As name suggests Web host can be used only for HTTP (eg tied for web application) only but generic host, which has been introduced in . Net core 3.0, can be used for Console application as well. Though the Generic host got included in . NET core 2.1 it was only used for non HTTP workloads.
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:
https://github.com/aspnet/AspNetCore/blob/1480b998660d2f77d0605376eefab6a83474ce07/src/DefaultBuilder/src/WebHost.cs#L280
For the difference, ConfigureWebHostDefaults
configures a web host with:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With