diff --git a/aspnetcore/diagnostics/code-analysis.md b/aspnetcore/diagnostics/code-analysis.md index 698b7902b6e2..3adf0c2a8228 100644 --- a/aspnetcore/diagnostics/code-analysis.md +++ b/aspnetcore/diagnostics/code-analysis.md @@ -1,60 +1,74 @@ --- -title: Code analysis in ASP.NET Core apps +title: Diagnostic Code Analysis in ASP.NET Core Apps author: tdykstra -description: Learn about source code analysis in ASP.NET Core +description: Review the list of diagnostic codes for ASP.NET Core and get details for specific diagnostic identifiers (IDs), such as ASP0007, BL0001, MVC1006, and so on. monikerRange: '>= aspnetcore-3.1' ms.author: tdykstra -ms.date: 07/08/2024 +ms.date: 04/21/2026 uid: diagnostics/code-analysis + +# customer intent: As an ASP.NET developer, I want to get details for specific diagnostic codes in ASP.NET Core, so I can understand the diagnostic messages in my apps. --- -# Code analysis in ASP.NET Core apps - -.NET compiler platform analyzers inspect application code for code quality and style issues. This document lists diagnostics for ASP.NET Core. For information on .NET diagnostics, see [Overview of .NET source code analysis](/dotnet/fundamentals/code-analysis/overview). - -The following list contains the diagnostics for ASP.NET Core. Not all of the diagnostics shown are available in older versions of ASP.NET Core. - -Diagnostic ID: - -* [ASP0000](xref:diagnostics/asp0000) -* [ASP0001](xref:diagnostics/asp0001) -* [ASP0003](xref:diagnostics/asp0003) -* [ASP0004](xref:diagnostics/asp0004) -* [ASP0005](xref:diagnostics/asp0005) -* [ASP0006](xref:diagnostics/asp0006) -* [ASP0007](xref:diagnostics/asp0007) -* [ASP0008](xref:diagnostics/asp0008) -* [ASP0009](xref:diagnostics/asp0009) -* [ASP0010](xref:diagnostics/asp0010) -* [ASP0011](xref:diagnostics/asp0011) -* [ASP0012](xref:diagnostics/asp0012) -* [ASP0013](xref:diagnostics/asp0013) -* [ASP0014](xref:diagnostics/asp0014) -* [ASP0015](xref:diagnostics/asp0015) -* [ASP0016](xref:diagnostics/asp0016) -* [ASP0017](xref:diagnostics/asp0017) -* [ASP0018](xref:diagnostics/asp0018) -* [ASP0019](xref:diagnostics/asp0019) -* [ASP0020](xref:diagnostics/asp0020) -* [ASP0021](xref:diagnostics/asp0021) -* [ASP0022](xref:diagnostics/asp0022) -* [ASP0023](xref:diagnostics/asp0023) -* [ASP0024](xref:diagnostics/asp0024) -* [ASP0025](xref:diagnostics/asp0025) -* [ASP0026](xref:diagnostics/asp0026) -* [ASP0027](xref:diagnostics/asp0027) -* [ASP0028](xref:diagnostics/asp0028) -* [BL0001](xref:diagnostics/bl0001) -* [BL0002](xref:diagnostics/bl0002) -* [BL0003](xref:diagnostics/bl0003) -* [BL0004](xref:diagnostics/bl0004) -* [BL0005](xref:diagnostics/bl0005) -* [BL0006](xref:diagnostics/bl0006) -* [BL0007](xref:diagnostics/bl0007) -* [BL0008](xref:diagnostics/bl0008) -* [MVC1000](xref:diagnostics/mvc1000) -* [MVC1001](xref:diagnostics/mvc1001) -* [MVC1002](xref:diagnostics/mvc1002) -* [MVC1003](xref:diagnostics/mvc1003) -* [MVC1004](xref:diagnostics/mvc1004) -* [MVC1005](xref:diagnostics/mvc1005) -* [MVC1006](xref:diagnostics/mvc1006) + +# Diagnostic code analysis in ASP.NET Core apps + +.NET compiler platform analyzers inspect application code for code quality and style issues. + +This article provides links to specific diagnostic messages for ASP.NET Core. For more information on .NET diagnostics, see [Overview of .NET source code analysis](/dotnet/fundamentals/code-analysis/overview). + +## Diagnostic codes + +The following table lists the diagnostics available for ASP.NET Core applications. + +> [!NOTE] +> Not all diagnostics are available in older versions of ASP.NET Core. + +| Diagnostic ID | Message | +| --- | --- | +| **[ASP0000](xref:diagnostics/asp0000)** | Do not call `IServiceCollection.BuildServiceProvider` in `ConfigureServices` | +| **[ASP0001](xref:diagnostics/asp0001)** | Authorization middleware is incorrectly configured | +| **[ASP0003](xref:diagnostics/asp0003)** | Do not use model binding attributes with route handlers | +| **[ASP0004](xref:diagnostics/asp0004)** | Do not use action results with route handlers | +| **[ASP0005](xref:diagnostics/asp0005)** | Do not place attribute on method called by route handler lambda | +| **[ASP0006](xref:diagnostics/asp0006)** | Do not use non-literal sequence numbers | +| **[ASP0007](xref:diagnostics/asp0007)** | Route parameter and argument optionality is mismatched | +| **[ASP0008](xref:diagnostics/asp0008)** | Do not use `ConfigureWebHost` with `WebApplicationBuilder.Host` | +| **[ASP0009](xref:diagnostics/asp0009)** | Do not use `Configure` with `WebApplicationBuilder.WebHost` | +| **[ASP0010](xref:diagnostics/asp0010)** | Do not use `UseStartup` with `WebApplicationBuilder.WebHost` | +| **[ASP0011](xref:diagnostics/asp0011)** | Suggest using `builder.Logging` over `Host.ConfigureLogging` or `WebHost.ConfigureLogging` | +| **[ASP0012](xref:diagnostics/asp0012)** | Suggest using `builder.Services` over `Host.ConfigureServices` or `WebHost.ConfigureServices` | +| **[ASP0013](xref:diagnostics/asp0013)** | Suggest switching from using `Configure` methods to `WebApplicationBuilder.Configuration` | +| **[ASP0014](xref:diagnostics/asp0014)** | Suggest using top level route registrations | +| **[ASP0015](xref:diagnostics/asp0015)** | Suggest using `IHeaderDictionary` properties | +| **[ASP0016](xref:diagnostics/asp0016)** | Do not return a value from `RequestDelegate` | +| **[ASP0017](xref:diagnostics/asp0017)** | Invalid route pattern | +| **[ASP0018](xref:diagnostics/asp0018)** | Unused route parameter | +| **[ASP0019](xref:diagnostics/asp0019)** | Suggest using `IHeaderDictionary.Append` or the indexer | +| **[ASP0020](xref:diagnostics/asp0020)** | Complex types referenced by route parameters must be parsable | +| **[ASP0021](xref:diagnostics/asp0021)** | Return type of the `BindAsync` method must be `ValueTask` | +| **[ASP0022](xref:diagnostics/asp0022)** | Route conflict detected between route handlers ([Minimal API apps](/aspnet/core/fundamentals/apis)) | +| **[ASP0023](xref:diagnostics/asp0023)** | Route conflict detected between route handlers | +| **[ASP0024](xref:diagnostics/asp0024)** | Route handler has multiple parameters with the `[FromBody]` attribute | +| **[ASP0025](xref:diagnostics/asp0025)** | Use `AddAuthorizationBuilder` to register authorization services and construct policies | +| **[ASP0026](xref:diagnostics/asp0026)** | `[Authorize]` is overridden by `[AllowAnonymous]` from "farther away" | +| **[ASP0027](xref:diagnostics/asp0027)** | Unnecessary `public Program` class declaration | +| **[ASP0028](xref:diagnostics/asp0028)** | Consider using `IPAddress.IPv6Any` instead of `IPAddress.Any` | +| **[BL0001](xref:diagnostics/bl0001)** | Component parameter should have public setters | +| **[BL0002](xref:diagnostics/bl0002)** | Component has multiple `CaptureUnmatchedValues` parameters | +| **[BL0003](xref:diagnostics/bl0003)** | Component parameter with `CaptureUnmatchedValues` has the wrong type | +| **[BL0004](xref:diagnostics/bl0004)** | Component parameter should be public | +| **[BL0005](xref:diagnostics/bl0005)** | Component parameter should not be set outside of its component | +| **[BL0006](xref:diagnostics/bl0006)** | Do not use RenderTree types | +| **[BL0007](xref:diagnostics/bl0007)** | Component parameter `{0}` should be auto property | +| **[BL0008](xref:diagnostics/bl0008)** | Component parameters should be auto properties | +| **[MVC1000](xref:diagnostics/mvc1000)** | Use of `IHtmlHelper.Partial` should be avoided | +| **[MVC1001](xref:diagnostics/mvc1001)** | Filters cannot be applied to page handler methods | +| **[MVC1002](xref:diagnostics/mvc1002)** | Route attribute cannot be applied to page handler methods | +| **[MVC1003](xref:diagnostics/mvc1003)** | Route attributes cannot be applied to page models | +| **[MVC1004](xref:diagnostics/mvc1004)** | Rename model bound parameter | +| **[MVC1005](xref:diagnostics/mvc1005)** | Cannot use `UseMvc` with Endpoint Routing | +| **[MVC1006](xref:diagnostics/mvc1006)** | Methods containing Tag Helpers (`TagHelpers`) must be async and return `Task` | + +## Related content + +- [Overview of .NET source code analysis](/dotnet/fundamentals/code-analysis/overview) \ No newline at end of file diff --git a/aspnetcore/fundamentals/host/web-host.md b/aspnetcore/fundamentals/host/web-host.md index 65424c85838a..f48afa2ef479 100644 --- a/aspnetcore/fundamentals/host/web-host.md +++ b/aspnetcore/fundamentals/host/web-host.md @@ -2,1604 +2,80 @@ title: ASP.NET Core Web Host author: tdykstra description: Learn about Web Host in ASP.NET Core, which is responsible for app startup and lifetime management. -monikerRange: '>= aspnetcore-3.1' ms.author: tdykstra ms.custom: mvc -ms.date: 09/06/2024 +ms.date: 04/21/2026 uid: fundamentals/host/web-host ---- -# ASP.NET Core Web Host - -[!INCLUDE[](~/includes/not-latest-version.md)] - -:::moniker range=">= aspnetcore-6.0" - -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. - -This article covers the Web Host, which remains available only for backward compatibility. The ASP.NET Core templates create a and , which is recommended for web apps. For more information on `WebApplicationBuilder` and `WebApplication`, see - -## Set up a host - -Create a host using an instance of . This is typically performed in the app's entry point, the `Main` method in `Program.cs`. A typical app calls to start setting up a host: - -```csharp -public class Program -{ - public static void Main(string[] args) - { - CreateWebHostBuilder(args).Build().Run(); - } - - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); -} -``` - -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. This separation is required if you use [Entity Framework Core tools](/ef/core/miscellaneous/cli/). The tools expect to find a `CreateWebHostBuilder` method that they can call at design time to configure the host without running the app. An alternative is to implement `IDesignTimeDbContextFactory`. For more information, see [Design-time DbContext Creation](/ef/core/miscellaneous/cli/dbcontext-creation). - -`CreateDefaultBuilder` performs the following tasks: - -* Configures [Kestrel](xref:fundamentals/servers/kestrel) server as the web server using the app's hosting configuration providers. For the Kestrel server's default options, see . -* Sets the [content root](xref:fundamentals/index#content-root) to the path returned by . -* Loads [host configuration](#host-configuration-values) from: - * Environment variables prefixed with `ASPNETCORE_` (for example, `ASPNETCORE_ENVIRONMENT`). - * Command-line arguments. -* Loads app configuration in the following order from: - * `appsettings.json`. - * `appsettings.{Environment}.json`. - * [User secrets](xref:security/app-secrets) when the app runs in the `Development` environment using the entry assembly. - * Environment variables. - * Command-line arguments. -* Configures [logging](xref:fundamentals/logging/index) for console and debug output. Logging includes [log filtering](xref:fundamentals/logging/index#apply-log-filter-rules-in-code) rules specified in a Logging configuration section of an `appsettings.json` or `appsettings.{Environment}.json` file. -* When running behind IIS with the [ASP.NET Core Module](xref:host-and-deploy/aspnet-core-module), `CreateDefaultBuilder` enables [IIS Integration](xref:host-and-deploy/iis/index), which configures the app's base address and port. IIS Integration also configures the app to [capture startup errors](#capture-startup-errors). For the IIS default options, see . -* Sets to `true` if the app's environment is `Development`. For more information, see [Scope validation](#scope-validation). - -The configuration defined by `CreateDefaultBuilder` can be overridden and augmented by , , and other methods and extension methods of . A few examples follow: - -* is used to specify additional `IConfiguration` for the app. The following `ConfigureAppConfiguration` call adds a delegate to include app configuration in the `appsettings.xml` file. `ConfigureAppConfiguration` may be called multiple times. Note that this configuration doesn't apply to the host (for example, server URLs or environment). See the [Host configuration values](#host-configuration-values) section. - - ```csharp - WebHost.CreateDefaultBuilder(args) - .ConfigureAppConfiguration((hostingContext, config) => - { - config.AddXmlFile("appsettings.xml", optional: true, reloadOnChange: true); - }) - ... - ``` - -* The following `ConfigureLogging` call adds a delegate to configure the minimum logging level () to . This setting overrides the settings in `appsettings.Development.json` (`LogLevel.Debug`) and `appsettings.Production.json` (`LogLevel.Error`) configured by `CreateDefaultBuilder`. `ConfigureLogging` may be called multiple times. - - ```csharp - WebHost.CreateDefaultBuilder(args) - .ConfigureLogging(logging => - { - logging.SetMinimumLevel(LogLevel.Warning); - }) - ... - ``` - -* The following call to `ConfigureKestrel` overrides the default [Limits.MaxRequestBodySize](xref:Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerLimits.MaxRequestBodySize%2A) of 30,000,000 bytes established when Kestrel was configured by `CreateDefaultBuilder`: - - ```csharp - WebHost.CreateDefaultBuilder(args) - .ConfigureKestrel((context, options) => - { - options.Limits.MaxRequestBodySize = 20000000; - }); - ``` - -The [content root](xref:fundamentals/index#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. This is the default used in [Visual Studio](https://visualstudio.microsoft.com) and the [dotnet new templates](/dotnet/core/tools/dotnet-new). - -For more information on app configuration, see . - -> [!NOTE] -> As an alternative to using the static `CreateDefaultBuilder` method, creating a host from is a supported approach with ASP.NET Core 2.x. - -When setting up a host, and methods can be provided. If a `Startup` class is specified, it must define a `Configure` method. For more information, see . Multiple calls to `ConfigureServices` append to one another. Multiple calls to `Configure` or `UseStartup` on the `WebHostBuilder` replace previous settings. - -## Host configuration values - - relies on the following approaches to set the host configuration values: - -* Host builder configuration, which includes environment variables with the format `ASPNETCORE_{configurationKey}`. For example, `ASPNETCORE_ENVIRONMENT`. -* Extensions such as and (see the [Override configuration](#override-configuration) section). -* and the associated key. 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](#override-configuration) in the next section. - -### Application Key (Name) - -The `IWebHostEnvironment.ApplicationName` property is automatically set when or is called during host construction. The value is set to the name of the assembly containing the app's entry point. To set the value explicitly, use the : - -**Key**: applicationName -**Type**: *string* -**Default**: The name of the assembly containing the app's entry point. -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_APPLICATIONNAME` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.ApplicationKey, "CustomApplicationName") -``` - -### Capture Startup Errors - -This setting controls the capture of startup errors. - -**Key**: captureStartupErrors -**Type**: *bool* (`true` or `1`) -**Default**: Defaults to `false` unless the app runs with Kestrel behind IIS, where the default is `true`. -**Set using**: `CaptureStartupErrors` -**Environment variable**: `ASPNETCORE_CAPTURESTARTUPERRORS` - -When `false`, errors during startup result in the host exiting. When `true`, the host captures exceptions during startup and attempts to start the server. - -```csharp -WebHost.CreateDefaultBuilder(args) - .CaptureStartupErrors(true) -``` - -### Content root - -This setting determines where ASP.NET Core begins searching for content files. - -**Key**: contentRoot -**Type**: *string* -**Default**: Defaults to the folder where the app assembly resides. -**Set using**: `UseContentRoot` -**Environment variable**: `ASPNETCORE_CONTENTROOT` - -The content root is also used as the base path for the [web root](xref:fundamentals/index#web-root). If the content root path doesn't exist, the host fails to start. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseContentRoot("c:\\") -``` - -For more information, see: - -* [Fundamentals: Content root](xref:fundamentals/index#content-root) -* [Web root](#web-root) - -### Detailed Errors - -Determines if detailed errors should be captured. - -**Key**: detailedErrors -**Type**: *bool* (`true` or `1`) -**Default**: false -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_DETAILEDERRORS` - -When enabled (or when the Environment is set to `Development`), the app captures detailed exceptions. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.DetailedErrorsKey, "true") -``` - -### Environment - -Sets the app's environment. - -**Key**: environment -**Type**: *string* -**Default**: Production -**Set using**: `UseEnvironment` -**Environment variable**: `ASPNETCORE_ENVIRONMENT` - -The environment can be set to any value. Framework-defined values include `Development`, `Staging`, and `Production`. Values aren't case sensitive. By default, the *Environment* is read from the `ASPNETCORE_ENVIRONMENT` environment variable. When using [Visual Studio](https://visualstudio.microsoft.com), environment variables may be set in the `launchSettings.json` file. For more information, see . - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseEnvironment(EnvironmentName.Development) -``` - -### Hosting Startup Assemblies - -Sets the app's hosting startup assemblies. - -**Key**: hostingStartupAssemblies -**Type**: *string* -**Default**: Empty string -**Set using**: `UseSetting` -**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. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.HostingStartupAssembliesKey, "assembly1;assembly2") -``` - -### HTTPS Port - -Set the HTTPS port to redirect to if you get a non-HTTPS connection. Used in [enforcing HTTPS](xref:security/enforcing-ssl). This setting doesn't cause the server to listen on the specified port. That is, it's possible to accidentally redirect requests to an unused port. - -**Key**: https_port -**Type**: *string* -**Default**: A default value isn't set. -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_HTTPS_PORT` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting("https_port", "8080") -``` - -### HTTPS Ports - -Set the ports to listen on for HTTPS connections. - -**Key**: https_ports -**Type**: *string* -**Default**: A default value isn't set. -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_HTTPS_PORTS` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting("https_ports", "8080") -``` - -### HTTP Ports - -Set the ports to listen on for HTTP connections. - -**Key**: http_ports -**Type**: *string* -**Default**: A default value isn't set. -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_HTTP_PORTS` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting("http_ports", "8080") -``` - -### Hosting Startup Exclude Assemblies - -A semicolon-delimited string of hosting startup assemblies to exclude on startup. - -**Key**: hostingStartupExcludeAssemblies -**Type**: *string* -**Default**: Empty string -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_HOSTINGSTARTUPEXCLUDEASSEMBLIES` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.HostingStartupExcludeAssembliesKey, "assembly1;assembly2") -``` - -### Prefer Hosting URLs - -Indicates whether the host should listen on the URLs configured with the `WebHostBuilder` instead of those configured with the `IServer` implementation. - -**Key**: preferHostingUrls -**Type**: *bool* (`true` or `1`) -**Default**: false -**Set using**: `PreferHostingUrls` -**Environment variable**: `ASPNETCORE_PREFERHOSTINGURLS` - -```csharp -WebHost.CreateDefaultBuilder(args) - .PreferHostingUrls(true) -``` - -### Prevent Hosting Startup - -Prevents the automatic loading of hosting startup assemblies, including hosting startup assemblies configured by the app's assembly. For more information, see . - -**Key**: preventHostingStartup -**Type**: *bool* (`true` or `1`) -**Default**: false -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_PREVENTHOSTINGSTARTUP` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.PreventHostingStartupKey, "true") -``` - -### Server URLs - -Indicates the IP addresses or host addresses with ports and protocols that the server should listen on for requests. - -**Key**: urls -**Type**: *string* -**Default**: http://localhost:5000 -**Set using**: `UseUrls` -**Environment variable**: `ASPNETCORE_URLS` - -Set to a semicolon-separated (;) list of URL prefixes to which the server should respond. For example, `http://localhost:123`. 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`). The protocol (`http://` or `https://`) must be included with each URL. Supported formats vary among servers. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseUrls("http://*:5000;http://localhost:5001;https://hostname:5002") -``` - -Kestrel has its own endpoint configuration API. For more information, see . - -### Shutdown Timeout - -Specifies the amount of time to wait for Web Host to shut down. - -**Key**: shutdownTimeoutSeconds -**Type**: *int* -**Default**: 5 -**Set using**: `UseShutdownTimeout` -**Environment variable**: `ASPNETCORE_SHUTDOWNTIMEOUTSECONDS` - -Although the key accepts an *int* with `UseSetting` (for example, `.UseSetting(WebHostDefaults.ShutdownTimeoutKey, "10")`), the extension method takes a . - -During the timeout period, hosting: - -* Triggers . -* 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. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseShutdownTimeout(TimeSpan.FromSeconds(10)) -``` - -### Startup Assembly - -Determines the assembly to search for the `Startup` class. - -**Key**: startupAssembly -**Type**: *string* -**Default**: The app's assembly -**Set using**: `UseStartup` -**Environment variable**: `ASPNETCORE_STARTUPASSEMBLY` - -The assembly by name (`string`) or type (`TStartup`) can be referenced. If multiple `UseStartup` methods are called, the last one takes precedence. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseStartup("StartupAssemblyName") -``` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseStartup() -``` - -### Web root - -Sets the relative path to the app's static assets. - -**Key**: webroot -**Type**: *string* -**Default**: The default is `wwwroot`. The path to *{content root}/wwwroot* must exist. If the path doesn't exist, a no-op file provider is used. -**Set using**: `UseWebRoot` -**Environment variable**: `ASPNETCORE_WEBROOT` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseWebRoot("public") -``` - -For more information, see: - -* [Fundamentals: Web root](xref:fundamentals/index#web-root) -* [Content root](#content-root) - -## Override configuration - -Use [Configuration](xref:fundamentals/configuration/index) to configure Web Host. In the following example, host configuration is optionally specified in a `hostsettings.json` file. Any configuration loaded from the `hostsettings.json` file may be overridden by command-line arguments. The built configuration (in `config`) is used to configure the host with . `IWebHostBuilder` configuration is added to the app's configuration, but the converse isn't true—`ConfigureAppConfiguration` doesn't affect the `IWebHostBuilder` configuration. - -Overriding the configuration provided by `UseUrls` with `hostsettings.json` config first, command-line argument config second: - -```csharp -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`: - -```json -{ - urls: "http://*:5005" -} -``` - -> [!NOTE] -> only copies keys from the provided `IConfiguration` to the host builder configuration. Therefore, setting `reloadOnChange: true` for JSON, INI, and XML settings files has no effect. - -To specify the host run on a particular URL, the desired value can be passed in from a command prompt when executing [dotnet run](/dotnet/core/tools/dotnet-run). The command-line argument overrides the `urls` value from the `hostsettings.json` file, and the server listens on port 8080: - -```dotnetcli -dotnet run --urls "http://*:8080" -``` - -## Manage the host - -**Run** - -The `Run` method starts the web app and blocks the calling thread until the host is shut down: - -```csharp -host.Run(); -``` - -**Start** - -Run the host in a non-blocking manner by calling its `Start` method: - -```csharp -using (host) -{ - host.Start(); - Console.ReadLine(); -} -``` - -If a list of URLs is passed to the `Start` method, it listens on the URLs specified: - -```csharp -var urls = new List() -{ - "http://*:5000", - "http://localhost:5001" -}; - -var host = new WebHostBuilder() - .UseKestrel() - .UseStartup() - .Start(urls.ToArray()); - -using (host) -{ - Console.ReadLine(); -} -``` - -The app can initialize and start a new host using the pre-configured defaults of `CreateDefaultBuilder` using a static convenience method. These methods start the server without console output and with wait for a break (Ctrl-C/SIGINT or SIGTERM): - -**Start(RequestDelegate app)** - -Start with a `RequestDelegate`: - -```csharp -using (var host = WebHost.Start(app => app.Response.WriteAsync("Hello, World!"))) -{ - Console.WriteLine("Use Ctrl-C to shutdown the host..."); - host.WaitForShutdown(); -} -``` - -Make a request in the browser to `http://localhost:5000` to receive the response "Hello World!" `WaitForShutdown` blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. - -**Start(string url, RequestDelegate app)** - -Start with a URL and `RequestDelegate`: - -```csharp -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(); -} -``` - -Produces the same result as **Start(RequestDelegate app)**, except the app responds on `http://localhost:8080`. - -**Start(Action\ routeBuilder)** - -Use an instance of `IRouteBuilder` ([Microsoft.AspNetCore.Routing](https://www.nuget.org/packages/Microsoft.AspNetCore.Routing/)) to use routing middleware: - -```csharp -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! | -| `http://localhost:5000/buenosdias/Catrina` | Buenos dias, Catrina! | -| `http://localhost:5000/throw/ooops!` | Throws an exception with string "ooops!" | -| `http://localhost:5000/throw` | Throws an exception with string "Uh oh!" | -| `http://localhost:5000/Sante/Kevin` | Sante, Kevin! | -| `http://localhost:5000` | Hello World! | - -`WaitForShutdown` blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. - -**Start(string url, Action\ routeBuilder)** - -Use a URL and an instance of `IRouteBuilder`: - -```csharp -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(); -} -``` - -Produces the same result as **Start(Action\ routeBuilder)**, except the app responds at `http://localhost:8080`. - -**StartWith(Action\ app)** - -Provide a delegate to configure an `IApplicationBuilder`: - -```csharp -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(); -} -``` - -Make a request in the browser to `http://localhost:5000` to receive the response "Hello World!" `WaitForShutdown` blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. - -**StartWith(string url, Action\ app)** - -Provide a URL and a delegate to configure an `IApplicationBuilder`: - -```csharp -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(); -} -``` - -Produces the same result as **StartWith(Action\ app)**, except the app responds on `http://localhost:8080`. - -## IWebHostEnvironment interface - -The `IWebHostEnvironment` interface provides information about the app's web hosting environment. Use [constructor injection](xref:fundamentals/dependency-injection) to obtain the `IWebHostEnvironment` in order to use its properties and extension methods: - -```csharp -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](xref:fundamentals/environments#environment-based-startup-class-and-methods) can be used to configure the app at startup based on the environment. Alternatively, inject the `IWebHostEnvironment` into the `Startup` constructor for use in `ConfigureServices`: - -```csharp -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; - } -} -``` - -> [!NOTE] -> In addition to the `IsDevelopment` extension method, `IWebHostEnvironment` offers `IsStaging`, `IsProduction`, and `IsEnvironment(string environmentName)` methods. For more information, see . - -The `IWebHostEnvironment` service can also be injected directly into the `Configure` method for setting up the processing pipeline: - -```csharp -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` can be injected into the `Invoke` method when creating custom [middleware](xref:fundamentals/middleware/write): - -```csharp -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; -} -``` - -## IHostApplicationLifetime interface - -`IHostApplicationLifetime` allows for post-startup and shutdown activities. 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. | - -```csharp -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` requests termination of the app. The following class uses `StopApplication` to gracefully shut down an app when the class's `Shutdown` method is called: - -```csharp -public class MyClass -{ - private readonly IHostApplicationLifetime _appLifetime; - - public MyClass(IHostApplicationLifetime appLifetime) - { - _appLifetime = appLifetime; - } - - public void Shutdown() - { - _appLifetime.StopApplication(); - } -} -``` - -## Scope validation - - sets to `true` if the app's environment is `Development`. - -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. - -The root service provider is created when 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. Validating service scopes catches these situations when `BuildServiceProvider` is called. - -To always validate scopes, including in the `Production` environment, configure the with on the host builder: - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseDefaultServiceProvider((context, options) => { - options.ValidateScopes = true; - }) -``` - -## Additional resources - -* -* -* - -:::moniker-end - -:::moniker range=">= aspnetcore-5.0 < aspnetcore-6.0" - -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. - -This article covers the Web Host, which remains available only for backward compatibility. The ASP.NET Core templates create a [.NET Generic Host](xref:fundamentals/host/generic-host), which is recommended for all app types. - -## Set up a host - -Create a host using an instance of . This is typically performed in the app's entry point, the `Main` method. - -In the project templates, `Main` is located in `Program.cs`. A typical app calls to start setting up a host: - -```csharp -public class Program -{ - public static void Main(string[] args) - { - CreateWebHostBuilder(args).Build().Run(); - } - - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); -} -``` - -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. This separation is required if you use [Entity Framework Core tools](/ef/core/miscellaneous/cli/). The tools expect to find a `CreateWebHostBuilder` method that they can call at design time to configure the host without running the app. An alternative is to implement `IDesignTimeDbContextFactory`. For more information, see [Design-time DbContext Creation](/ef/core/miscellaneous/cli/dbcontext-creation). - -`CreateDefaultBuilder` performs the following tasks: - -* Configures [Kestrel](xref:fundamentals/servers/kestrel) server as the web server using the app's hosting configuration providers. For the Kestrel server's default options, see . -* Sets the [content root](xref:fundamentals/index#content-root) to the path returned by . -* Loads [host configuration](#host-configuration-values) from: - * Environment variables prefixed with `ASPNETCORE_` (for example, `ASPNETCORE_ENVIRONMENT`). - * Command-line arguments. -* Loads app configuration in the following order from: - * `appsettings.json`. - * `appsettings.{Environment}.json`. - * [User secrets](xref:security/app-secrets) when the app runs in the `Development` environment using the entry assembly. - * Environment variables. - * Command-line arguments. -* Configures [logging](xref:fundamentals/logging/index) for console and debug output. Logging includes [log filtering](xref:fundamentals/logging/index#apply-log-filter-rules-in-code) rules specified in a Logging configuration section of an `appsettings.json` or `appsettings.{Environment}.json` file. -* When running behind IIS with the [ASP.NET Core Module](xref:host-and-deploy/aspnet-core-module), `CreateDefaultBuilder` enables [IIS Integration](xref:host-and-deploy/iis/index), which configures the app's base address and port. IIS Integration also configures the app to [capture startup errors](#capture-startup-errors). For the IIS default options, see . -* Sets to `true` if the app's environment is `Development`. For more information, see [Scope validation](#scope-validation). - -The configuration defined by `CreateDefaultBuilder` can be overridden and augmented by , , and other methods and extension methods of . A few examples follow: - -* is used to specify additional `IConfiguration` for the app. The following `ConfigureAppConfiguration` call adds a delegate to include app configuration in the `appsettings.xml` file. `ConfigureAppConfiguration` may be called multiple times. Note that this configuration doesn't apply to the host (for example, server URLs or environment). See the [Host configuration values](#host-configuration-values) section. - - ```csharp - WebHost.CreateDefaultBuilder(args) - .ConfigureAppConfiguration((hostingContext, config) => - { - config.AddXmlFile("appsettings.xml", optional: true, reloadOnChange: true); - }) - ... - ``` - -* The following `ConfigureLogging` call adds a delegate to configure the minimum logging level () to . This setting overrides the settings in `appsettings.Development.json` (`LogLevel.Debug`) and `appsettings.Production.json` (`LogLevel.Error`) configured by `CreateDefaultBuilder`. `ConfigureLogging` may be called multiple times. - - ```csharp - WebHost.CreateDefaultBuilder(args) - .ConfigureLogging(logging => - { - logging.SetMinimumLevel(LogLevel.Warning); - }) - ... - ``` - -* The following call to `ConfigureKestrel` overrides the default [Limits.MaxRequestBodySize](xref:Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerLimits.MaxRequestBodySize%2A) of 30,000,000 bytes established when Kestrel was configured by `CreateDefaultBuilder`: - - ```csharp - WebHost.CreateDefaultBuilder(args) - .ConfigureKestrel((context, options) => - { - options.Limits.MaxRequestBodySize = 20000000; - }); - ``` - -The [content root](xref:fundamentals/index#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. This is the default used in [Visual Studio](https://visualstudio.microsoft.com) and the [dotnet new templates](/dotnet/core/tools/dotnet-new). - -For more information on app configuration, see . - -> [!NOTE] -> As an alternative to using the static `CreateDefaultBuilder` method, creating a host from is a supported approach with ASP.NET Core 2.x. - -When setting up a host, and methods can be provided. If a `Startup` class is specified, it must define a `Configure` method. For more information, see . Multiple calls to `ConfigureServices` append to one another. Multiple calls to `Configure` or `UseStartup` on the `WebHostBuilder` replace previous settings. - -## Host configuration values - - relies on the following approaches to set the host configuration values: - -* Host builder configuration, which includes environment variables with the format `ASPNETCORE_{configurationKey}`. For example, `ASPNETCORE_ENVIRONMENT`. -* Extensions such as and (see the [Override configuration](#override-configuration) section). -* and the associated key. 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](#override-configuration) in the next section. - -### Application Key (Name) - -The `IWebHostEnvironment.ApplicationName` property is automatically set when or is called during host construction. The value is set to the name of the assembly containing the app's entry point. To set the value explicitly, use the : - -**Key**: applicationName -**Type**: *string* -**Default**: The name of the assembly containing the app's entry point. -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_APPLICATIONNAME` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.ApplicationKey, "CustomApplicationName") -``` - -### Capture Startup Errors - -This setting controls the capture of startup errors. - -**Key**: captureStartupErrors -**Type**: *bool* (`true` or `1`) -**Default**: Defaults to `false` unless the app runs with Kestrel behind IIS, where the default is `true`. -**Set using**: `CaptureStartupErrors` -**Environment variable**: `ASPNETCORE_CAPTURESTARTUPERRORS` - -When `false`, errors during startup result in the host exiting. When `true`, the host captures exceptions during startup and attempts to start the server. - -```csharp -WebHost.CreateDefaultBuilder(args) - .CaptureStartupErrors(true) -``` - -### Content root - -This setting determines where ASP.NET Core begins searching for content files. - -**Key**: contentRoot -**Type**: *string* -**Default**: Defaults to the folder where the app assembly resides. -**Set using**: `UseContentRoot` -**Environment variable**: `ASPNETCORE_CONTENTROOT` - -The content root is also used as the base path for the [web root](xref:fundamentals/index#web-root). If the content root path doesn't exist, the host fails to start. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseContentRoot("c:\\") -``` - -For more information, see: - -* [Fundamentals: Content root](xref:fundamentals/index#content-root) -* [Web root](#web-root) - -### Detailed Errors - -Determines if detailed errors should be captured. - -**Key**: detailedErrors -**Type**: *bool* (`true` or `1`) -**Default**: false -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_DETAILEDERRORS` - -When enabled (or when the Environment is set to `Development`), the app captures detailed exceptions. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.DetailedErrorsKey, "true") -``` - -### Environment - -Sets the app's environment. - -**Key**: environment -**Type**: *string* -**Default**: Production -**Set using**: `UseEnvironment` -**Environment variable**: `ASPNETCORE_ENVIRONMENT` - -The environment can be set to any value. Framework-defined values include `Development`, `Staging`, and `Production`. Values aren't case sensitive. By default, the *Environment* is read from the `ASPNETCORE_ENVIRONMENT` environment variable. When using [Visual Studio](https://visualstudio.microsoft.com), environment variables may be set in the `launchSettings.json` file. For more information, see . - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseEnvironment(EnvironmentName.Development) -``` - -### Hosting Startup Assemblies - -Sets the app's hosting startup assemblies. - -**Key**: hostingStartupAssemblies -**Type**: *string* -**Default**: Empty string -**Set using**: `UseSetting` -**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. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.HostingStartupAssembliesKey, "assembly1;assembly2") -``` - -### HTTPS Port - -Set the HTTPS redirect port. Used in [enforcing HTTPS](xref:security/enforcing-ssl). - -**Key**: https_port -**Type**: *string* -**Default**: A default value isn't set. -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_HTTPS_PORTS` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting("https_port", "8080") -``` - -### Hosting Startup Exclude Assemblies - -A semicolon-delimited string of hosting startup assemblies to exclude on startup. - -**Key**: hostingStartupExcludeAssemblies -**Type**: *string* -**Default**: Empty string -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_HOSTINGSTARTUPEXCLUDEASSEMBLIES` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.HostingStartupExcludeAssembliesKey, "assembly1;assembly2") -``` - -### Prefer Hosting URLs - -Indicates whether the host should listen on the URLs configured with the `WebHostBuilder` instead of those configured with the `IServer` implementation. - -**Key**: preferHostingUrls -**Type**: *bool* (`true` or `1`) -**Default**: false -**Set using**: `PreferHostingUrls` -**Environment variable**: `ASPNETCORE_PREFERHOSTINGURLS` - -```csharp -WebHost.CreateDefaultBuilder(args) - .PreferHostingUrls(true) -``` - -### Prevent Hosting Startup - -Prevents the automatic loading of hosting startup assemblies, including hosting startup assemblies configured by the app's assembly. For more information, see . - -**Key**: preventHostingStartup -**Type**: *bool* (`true` or `1`) -**Default**: false -**Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_PREVENTHOSTINGSTARTUP` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseSetting(WebHostDefaults.PreventHostingStartupKey, "true") -``` - -### Server URLs - -Indicates the IP addresses or host addresses with ports and protocols that the server should listen on for requests. - -**Key**: urls -**Type**: *string* -**Default**: http://localhost:5000 -**Set using**: `UseUrls` -**Environment variable**: `ASPNETCORE_URLS` - -Set to a semicolon-separated (;) list of URL prefixes to which the server should respond. For example, `http://localhost:123`. 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`). The protocol (`http://` or `https://`) must be included with each URL. Supported formats vary among servers. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseUrls("http://*:5000;http://localhost:5001;https://hostname:5002") -``` - -Kestrel has its own endpoint configuration API. For more information, see . - -### Shutdown Timeout - -Specifies the amount of time to wait for Web Host to shut down. - -**Key**: shutdownTimeoutSeconds -**Type**: *int* -**Default**: 5 -**Set using**: `UseShutdownTimeout` -**Environment variable**: `ASPNETCORE_SHUTDOWNTIMEOUTSECONDS` - -Although the key accepts an *int* with `UseSetting` (for example, `.UseSetting(WebHostDefaults.ShutdownTimeoutKey, "10")`), the extension method takes a . - -During the timeout period, hosting: - -* Triggers . -* 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. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseShutdownTimeout(TimeSpan.FromSeconds(10)) -``` - -### Startup Assembly - -Determines the assembly to search for the `Startup` class. - -**Key**: startupAssembly -**Type**: *string* -**Default**: The app's assembly -**Set using**: `UseStartup` -**Environment variable**: `ASPNETCORE_STARTUPASSEMBLY` - -The assembly by name (`string`) or type (`TStartup`) can be referenced. If multiple `UseStartup` methods are called, the last one takes precedence. - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseStartup("StartupAssemblyName") -``` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseStartup() -``` - -### Web root - -Sets the relative path to the app's static assets. - -**Key**: webroot -**Type**: *string* -**Default**: The default is `wwwroot`. The path to *{content root}/wwwroot* must exist. If the path doesn't exist, a no-op file provider is used. -**Set using**: `UseWebRoot` -**Environment variable**: `ASPNETCORE_WEBROOT` - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseWebRoot("public") -``` - -For more information, see: - -* [Fundamentals: Web root](xref:fundamentals/index#web-root) -* [Content root](#content-root) - -## Override configuration - -Use [Configuration](xref:fundamentals/configuration/index) to configure Web Host. In the following example, host configuration is optionally specified in a `hostsettings.json` file. Any configuration loaded from the `hostsettings.json` file may be overridden by command-line arguments. The built configuration (in `config`) is used to configure the host with . `IWebHostBuilder` configuration is added to the app's configuration, but the converse isn't true—`ConfigureAppConfiguration` doesn't affect the `IWebHostBuilder` configuration. - -Overriding the configuration provided by `UseUrls` with `hostsettings.json` config first, command-line argument config second: - -```csharp -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`: - -```json -{ - urls: "http://*:5005" -} -``` - -> [!NOTE] -> only copies keys from the provided `IConfiguration` to the host builder configuration. Therefore, setting `reloadOnChange: true` for JSON, INI, and XML settings files has no effect. - -To specify the host run on a particular URL, the desired value can be passed in from a command prompt when executing [dotnet run](/dotnet/core/tools/dotnet-run). The command-line argument overrides the `urls` value from the `hostsettings.json` file, and the server listens on port 8080: - -```dotnetcli -dotnet run --urls "http://*:8080" -``` - -## Manage the host - -**Run** - -The `Run` method starts the web app and blocks the calling thread until the host is shut down: - -```csharp -host.Run(); -``` - -**Start** - -Run the host in a non-blocking manner by calling its `Start` method: - -```csharp -using (host) -{ - host.Start(); - Console.ReadLine(); -} -``` - -If a list of URLs is passed to the `Start` method, it listens on the URLs specified: - -```csharp -var urls = new List() -{ - "http://*:5000", - "http://localhost:5001" -}; - -var host = new WebHostBuilder() - .UseKestrel() - .UseStartup() - .Start(urls.ToArray()); - -using (host) -{ - Console.ReadLine(); -} -``` - -The app can initialize and start a new host using the pre-configured defaults of `CreateDefaultBuilder` using a static convenience method. These methods start the server without console output and with wait for a break (Ctrl-C/SIGINT or SIGTERM): - -**Start(RequestDelegate app)** - -Start with a `RequestDelegate`: - -```csharp -using (var host = WebHost.Start(app => app.Response.WriteAsync("Hello, World!"))) -{ - Console.WriteLine("Use Ctrl-C to shutdown the host..."); - host.WaitForShutdown(); -} -``` - -Make a request in the browser to `http://localhost:5000` to receive the response "Hello World!" `WaitForShutdown` blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. - -**Start(string url, RequestDelegate app)** - -Start with a URL and `RequestDelegate`: - -```csharp -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(); -} -``` - -Produces the same result as **Start(RequestDelegate app)**, except the app responds on `http://localhost:8080`. - -**Start(Action\ routeBuilder)** - -Use an instance of `IRouteBuilder` ([Microsoft.AspNetCore.Routing](https://www.nuget.org/packages/Microsoft.AspNetCore.Routing/)) to use routing middleware: - -```csharp -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! | -| `http://localhost:5000/buenosdias/Catrina` | Buenos dias, Catrina! | -| `http://localhost:5000/throw/ooops!` | Throws an exception with string "ooops!" | -| `http://localhost:5000/throw` | Throws an exception with string "Uh oh!" | -| `http://localhost:5000/Sante/Kevin` | Sante, Kevin! | -| `http://localhost:5000` | Hello World! | - -`WaitForShutdown` blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. - -**Start(string url, Action\ routeBuilder)** - -Use a URL and an instance of `IRouteBuilder`: - -```csharp -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(); -} -``` - -Produces the same result as **Start(Action\ routeBuilder)**, except the app responds at `http://localhost:8080`. - -**StartWith(Action\ app)** - -Provide a delegate to configure an `IApplicationBuilder`: - -```csharp -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(); -} -``` - -Make a request in the browser to `http://localhost:5000` to receive the response "Hello World!" `WaitForShutdown` blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. - -**StartWith(string url, Action\ app)** - -Provide a URL and a delegate to configure an `IApplicationBuilder`: - -```csharp -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(); -} -``` - -Produces the same result as **StartWith(Action\ app)**, except the app responds on `http://localhost:8080`. - -## IWebHostEnvironment interface - -The `IWebHostEnvironment` interface provides information about the app's web hosting environment. Use [constructor injection](xref:fundamentals/dependency-injection) to obtain the `IWebHostEnvironment` in order to use its properties and extension methods: - -```csharp -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](xref:fundamentals/environments#environment-based-startup-class-and-methods) can be used to configure the app at startup based on the environment. Alternatively, inject the `IWebHostEnvironment` into the `Startup` constructor for use in `ConfigureServices`: - -```csharp -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; - } -} -``` - -> [!NOTE] -> In addition to the `IsDevelopment` extension method, `IWebHostEnvironment` offers `IsStaging`, `IsProduction`, and `IsEnvironment(string environmentName)` methods. For more information, see . - -The `IWebHostEnvironment` service can also be injected directly into the `Configure` method for setting up the processing pipeline: - -```csharp -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` can be injected into the `Invoke` method when creating custom [middleware](xref:fundamentals/middleware/write): - -```csharp -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; -} -``` - -## IHostApplicationLifetime interface - -`IHostApplicationLifetime` allows for post-startup and shutdown activities. 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. | -```csharp -public class Startup -{ - public void Configure(IApplicationBuilder app, IHostApplicationLifetime appLifetime) - { - appLifetime.ApplicationStarted.Register(OnStarted); - appLifetime.ApplicationStopping.Register(OnStopping); - appLifetime.ApplicationStopped.Register(OnStopped); +# customer intent: As an ASP.NET developer, I want to explore the Web Host in ASP.NET Core, so I can configure startup and management for my web app. +--- +# ASP.NET Core Web Host - Console.CancelKeyPress += (sender, eventArgs) => - { - appLifetime.StopApplication(); - // Don't terminate the process immediately, wait for the Main thread to exit gracefully. - eventArgs.Cancel = true; - }; - } +[!INCLUDE[](~/includes/not-latest-version.md)] - private void OnStarted() - { - // Perform post-startup activities here - } +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. - private void OnStopping() - { - // Perform on-stopping activities here - } +This article covers the Web Host, which remains available only for backward compatibility. The ASP.NET Core templates create a and , which is recommended for web apps. For more information on `WebApplicationBuilder` and `WebApplication`, see . - private void OnStopped() - { - // Perform post-stopped activities here - } -} -``` +## Set up a host -`StopApplication` requests termination of the app. The following class uses `StopApplication` to gracefully shut down an app when the class's `Shutdown` method is called: +Create a host by using an instance of . This task is typically performed in the app's entry point, the `Main` method in the _Program.cs_ file. A typical app calls the method to start setting up a host: ```csharp -public class MyClass +public class Program { - private readonly IHostApplicationLifetime _appLifetime; - - public MyClass(IHostApplicationLifetime appLifetime) + public static void Main(string[] args) { - _appLifetime = appLifetime; + CreateWebHostBuilder(args).Build().Run(); } - public void Shutdown() - { - _appLifetime.StopApplication(); - } + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup(); } ``` -## Scope validation - - sets to `true` if the app's environment is `Development`. - -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. - -The root service provider is created when 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. Validating service scopes catches these situations when `BuildServiceProvider` is called. - -To always validate scopes, including in the `Production` environment, configure the with on the host builder: - -```csharp -WebHost.CreateDefaultBuilder(args) - .UseDefaultServiceProvider((context, options) => { - options.ValidateScopes = true; - }) -``` +The code that calls `CreateDefaultBuilder` is in a method named `CreateWebHostBuilder`, which separates it from the code in `Main` that calls the `Run` method on the builder object. The separation is required if you use [Entity Framework Core tools](/ef/core/cli/). The tools expect to find a `CreateWebHostBuilder` method that they can call at design time to configure the host without running the app. An alternative is to create an instance of `IDesignTimeDBContextfactory`. For more information, see [Design-time DbContext Creation](/ef/core/cli/dbcontext-creation). -## Additional resources +The `CreateDefaultBuilder` method performs the following tasks: -* -* -* +* Configures [Kestrel](xref:fundamentals/servers/kestrel) server as the web server by using the app's hosting configuration providers. For the Kestrel server's default options, see . -:::moniker-end +* Sets the [content root](xref:fundamentals/index#content-root) to the path returned by . -:::moniker range="< aspnetcore-5.0" +* Loads the [host configuration](#set-web-host-configuration-values) from the following sources: + * Environment variables prefixed with `ASPNETCORE_` (for example, `ASPNETCORE_ENVIRONMENT`) + * Command-line arguments -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. +* Loads the app configuration in the following order: + * _appsettings.json_ file + * _appsettings.{Environment}.json_ file + * [User secrets](xref:security/app-secrets) (Loaded when the app runs in the `Development` environment by using the entry assembly.) + * Environment variables + * Command-line arguments -This article covers the Web Host, which remains available only for backward compatibility. The ASP.NET Core templates create a [.NET Generic Host](xref:fundamentals/host/generic-host), which is recommended for all app types. +* Configures [logging](xref:fundamentals/logging/index) for console and debug output. Logging includes [log filtering](xref:fundamentals/logging/index#apply-log-filter-rules-in-code) rules specified in a Logging configuration section of an _appsettings.json_ or _appsettings.{Environment}.json_ file. -## Set up a host +* When the application runs behind IIS with the [ASP.NET Core Module](xref:host-and-deploy/aspnet-core-module), `CreateDefaultBuilder` enables [IIS Integration](xref:host-and-deploy/iis/index), which configures the application base address and port. IIS Integration also configures the app to [capture startup errors](#capture-startup-errors). For the IIS default options, see . -Create a host using an instance of . This is typically performed in the app's entry point, the `Main` method. +* Sets the property to `true`, if the application environment is `Development`. For more information, see [Configure scope validation](#configure-scope-validation). -In the project templates, `Main` is located in `Program.cs`. A typical app calls to start setting up a host: +The [content root](xref:fundamentals/index#content-root) determines where the host searches for content files, such as MVC view files. When the app launches from the project root folder, that folder is used as the content root. This behavior is the default for [Visual Studio](https://visualstudio.microsoft.com) and the [dotnet new templates](/dotnet/core/tools/dotnet-new). -```csharp -public class Program -{ - public static void Main(string[] args) - { - CreateWebHostBuilder(args).Build().Run(); - } +For more information on app configuration, see . - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); -} -``` +> [!NOTE] +> As an alternative to using the static `CreateDefaultBuilder` method, you can create a host from with ASP.NET Core 2.x. -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. This separation is required if you use [Entity Framework Core tools](/ef/core/miscellaneous/cli/). The tools expect to find a `CreateWebHostBuilder` method that they can call at design time to configure the host without running the app. An alternative is to implement `IDesignTimeDbContextFactory`. For more information, see [Design-time DbContext Creation](/ef/core/miscellaneous/cli/dbcontext-creation). +When you set up a host, you can use the and methods. If a `Startup` class is specified, it must define a `Configure` method. For more information, see . Multiple calls to `ConfigureServices` append each other. Multiple calls to `Configure` or `UseStartup` on the `WebHostBuilder` instance replace any previous settings. -`CreateDefaultBuilder` performs the following tasks: +### Methods for overriding the configuration -* Configures [Kestrel](xref:fundamentals/servers/kestrel) server as the web server using the app's hosting configuration providers. For the Kestrel server's default options, see . -* Sets the [content root](xref:fundamentals/index#content-root) to the path returned by . -* Loads [host configuration](#host-configuration-values) from: - * Environment variables prefixed with `ASPNETCORE_` (for example, `ASPNETCORE_ENVIRONMENT`). - * Command-line arguments. -* Loads app configuration in the following order from: - * `appsettings.json`. - * `appsettings.{Environment}.json`. - * [User secrets](xref:security/app-secrets) when the app runs in the `Development` environment using the entry assembly. - * Environment variables. - * Command-line arguments. -* Configures [logging](xref:fundamentals/logging/index) for console and debug output. Logging includes [log filtering](xref:fundamentals/logging/index#apply-log-filter-rules-in-code) rules specified in a Logging configuration section of an `appsettings.json` or `appsettings.{Environment}.json` file. -* When running behind IIS with the [ASP.NET Core Module](xref:host-and-deploy/aspnet-core-module), `CreateDefaultBuilder` enables [IIS Integration](xref:host-and-deploy/iis/index), which configures the app's base address and port. IIS Integration also configures the app to [capture startup errors](#capture-startup-errors). For the IIS default options, see . -* Sets to `true` if the app's environment is `Development`. For more information, see [Scope validation](#scope-validation). +You can override and augment the configuration defined by `CreateDefaultBuilder`. Use the and methods, and other methods and extension methods of . -The configuration defined by `CreateDefaultBuilder` can be overridden and augmented by , , and other methods and extension methods of . A few examples follow: +Here are some examples: -* is used to specify additional `IConfiguration` for the app. The following `ConfigureAppConfiguration` call adds a delegate to include app configuration in the `appsettings.xml` file. `ConfigureAppConfiguration` may be called multiple times. Note that this configuration doesn't apply to the host (for example, server URLs or environment). See the [Host configuration values](#host-configuration-values) section. +* is used to specify other `IConfiguration` properties for the app. The following call to the `ConfigureAppConfiguration` method adds a delegate to include app configuration in the _appsettings.xml_ file. `ConfigureAppConfiguration` can be called multiple times. This configuration doesn't apply to the host (for example, server URLs or environment). For more information, see the [Host configuration values](#set-web-host-configuration-values) section. ```csharp WebHost.CreateDefaultBuilder(args) @@ -1610,7 +86,7 @@ The configuration defined by `CreateDefaultBuilder` can be overridden and augmen ... ``` -* The following `ConfigureLogging` call adds a delegate to configure the minimum logging level () to . This setting overrides the settings in `appsettings.Development.json` (`LogLevel.Debug`) and `appsettings.Production.json` (`LogLevel.Error`) configured by `CreateDefaultBuilder`. `ConfigureLogging` may be called multiple times. +* The following `ConfigureLogging` call adds a delegate to configure the minimum logging level () to . This setting overrides the settings in the _appsettings.Development.json_ file (`LogLevel.Debug`) and _appsettings.Production.json_ file (`LogLevel.Error`) configured by the `CreateDefaultBuilder` method. `ConfigureLogging` can be called multiple times. ```csharp WebHost.CreateDefaultBuilder(args) @@ -1621,7 +97,7 @@ The configuration defined by `CreateDefaultBuilder` can be overridden and augmen ... ``` -* The following call to `ConfigureKestrel` overrides the default [Limits.MaxRequestBodySize](xref:Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerLimits.MaxRequestBodySize%2A) of 30,000,000 bytes established when Kestrel was configured by `CreateDefaultBuilder`: +* The following call to `ConfigureKestrel` overrides the default [Limits.MaxRequestBodySize](xref:Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerLimits.MaxRequestBodySize%2A) of 30,000,000 bytes established when Kestrel is configured with the `CreateDefaultBuilder` method: ```csharp WebHost.CreateDefaultBuilder(args) @@ -1631,28 +107,21 @@ The configuration defined by `CreateDefaultBuilder` can be overridden and augmen }); ``` -The [content root](xref:fundamentals/index#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. This is the default used in [Visual Studio](https://visualstudio.microsoft.com) and the [dotnet new templates](/dotnet/core/tools/dotnet-new). - -For more information on app configuration, see . - -> [!NOTE] -> As an alternative to using the static `CreateDefaultBuilder` method, creating a host from is a supported approach with ASP.NET Core 2.x. +## Set Web Host configuration values -When setting up a host, and methods can be provided. If a `Startup` class is specified, it must define a `Configure` method. For more information, see . Multiple calls to `ConfigureServices` append to one another. Multiple calls to `Configure` or `UseStartup` on the `WebHostBuilder` replace previous settings. +The instance relies on the following approaches to set the host configuration values: -## Host configuration values +* The host builder configuration, which includes environment variables that use the format `ASPNETCORE_{configurationKey}`. For example, `ASPNETCORE_ENVIRONMENT`. - relies on the following approaches to set the host configuration values: +* Extensions, such as and . For more information, see [Override the Web Host configuration](#override-the-web-host-configuration). -* Host builder configuration, which includes environment variables with the format `ASPNETCORE_{configurationKey}`. For example, `ASPNETCORE_ENVIRONMENT`. -* Extensions such as and (see the [Override configuration](#override-configuration) section). -* and the associated key. When setting a value with `UseSetting`, the value is set as a string regardless of the type. +* The method and the associated key. When you set 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](#override-configuration) in the next section. +The host uses whichever option sets a value last. For more information, see [Override the Web Host configuration](#override-the-web-host-configuration). ### Application Key (Name) -The `IWebHostEnvironment.ApplicationName` property is automatically set when or is called during host construction. The value is set to the name of the assembly containing the app's entry point. To set the value explicitly, use the : +Defines the name of the assembly that contains the application entry point. **Key**: applicationName **Type**: *string* @@ -1660,6 +129,8 @@ The `IWebHostEnvironment.ApplicationName` property is automatically set when or method is called during host construction. To set the value explicitly, use the field. + ```csharp WebHost.CreateDefaultBuilder(args) .UseSetting(WebHostDefaults.ApplicationKey, "CustomApplicationName") @@ -1667,7 +138,7 @@ WebHost.CreateDefaultBuilder(args) ### Capture Startup Errors -This setting controls the capture of startup errors. +Controls the capture of startup errors. **Key**: captureStartupErrors **Type**: *bool* (`true` or `1`) @@ -1675,7 +146,7 @@ This setting controls the capture of startup errors. **Set using**: `CaptureStartupErrors` **Environment variable**: `ASPNETCORE_CAPTURESTARTUPERRORS` -When `false`, errors during startup result in the host exiting. When `true`, the host captures exceptions during startup and attempts to start the server. +When set to `false`, errors during startup result in the host exiting. When set to `true`, the host captures exceptions during startup and attempts to start the server. ```csharp WebHost.CreateDefaultBuilder(args) @@ -1684,7 +155,7 @@ WebHost.CreateDefaultBuilder(args) ### Content root -This setting determines where ASP.NET Core begins searching for content files. +Determines where ASP.NET Core begins searching for content files. **Key**: contentRoot **Type**: *string* @@ -1706,15 +177,15 @@ For more information, see: ### Detailed Errors -Determines if detailed errors should be captured. +Determines whether to capture detailed errors. **Key**: detailedErrors **Type**: *bool* (`true` or `1`) -**Default**: false +**Default**: `false` **Set using**: `UseSetting` **Environment variable**: `ASPNETCORE_DETAILEDERRORS` -When enabled (or when the Environment is set to `Development`), the app captures detailed exceptions. +When enabled (or when the Environment value is set to `Development`), the app captures detailed exceptions. ```csharp WebHost.CreateDefaultBuilder(args) @@ -1731,7 +202,9 @@ Sets the app's environment. **Set using**: `UseEnvironment` **Environment variable**: `ASPNETCORE_ENVIRONMENT` -The environment can be set to any value. Framework-defined values include `Development`, `Staging`, and `Production`. Values aren't case sensitive. By default, the *Environment* is read from the `ASPNETCORE_ENVIRONMENT` environment variable. When using [Visual Studio](https://visualstudio.microsoft.com), environment variables may be set in the `launchSettings.json` file. For more information, see . +The environment can be set to any value. Framework-defined values include `Development`, `Staging`, and `Production`. Values aren't case sensitive. + +By default, the *Environment* is read from the `ASPNETCORE_ENVIRONMENT` environment variable. When you use [Visual Studio](https://visualstudio.microsoft.com), environment variables can be set in the _launchSettings.json_ file. For more information, see . ```csharp WebHost.CreateDefaultBuilder(args) @@ -1740,7 +213,7 @@ WebHost.CreateDefaultBuilder(args) ### Hosting Startup Assemblies -Sets the app's hosting startup assemblies. +Provides a semicolon-delimited string of hosting startup assemblies to load on startup. **Key**: hostingStartupAssemblies **Type**: *string* @@ -1748,8 +221,6 @@ Sets the app's hosting startup assemblies. **Set using**: `UseSetting` **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. ```csharp @@ -1759,13 +230,15 @@ WebHost.CreateDefaultBuilder(args) ### HTTPS Port -Set the HTTPS redirect port. Used in [enforcing HTTPS](xref:security/enforcing-ssl). +Set the HTTPS port for redirection if you get a non-HTTPS connection. **Key**: https_port **Type**: *string* **Default**: A default value isn't set. **Set using**: `UseSetting` -**Environment variable**: `ASPNETCORE_HTTPS_PORTS` +**Environment variable**: `ASPNETCORE_HTTPS_PORT` + +This setting is used in [enforcing HTTPS](xref:security/enforcing-ssl). This setting doesn't cause the server to listen on the specified port. That is, it's possible to accidentally redirect requests to an unused port. ```csharp WebHost.CreateDefaultBuilder(args) @@ -1774,7 +247,7 @@ WebHost.CreateDefaultBuilder(args) ### Hosting Startup Exclude Assemblies -A semicolon-delimited string of hosting startup assemblies to exclude on startup. +Provides a semicolon-delimited string of hosting startup assemblies to exclude on startup. **Key**: hostingStartupExcludeAssemblies **Type**: *string* @@ -1789,11 +262,11 @@ WebHost.CreateDefaultBuilder(args) ### Prefer Hosting URLs -Indicates whether the host should listen on the URLs configured with the `WebHostBuilder` instead of those configured with the `IServer` implementation. +Indicates whether the host should listen on the URLs configured with the `WebHostBuilder` instead of the URLs configured with the `IServer` implementation. **Key**: preferHostingUrls **Type**: *bool* (`true` or `1`) -**Default**: false +**Default**: `false` **Set using**: `PreferHostingUrls` **Environment variable**: `ASPNETCORE_PREFERHOSTINGURLS` @@ -1808,7 +281,7 @@ Prevents the automatic loading of hosting startup assemblies, including hosting **Key**: preventHostingStartup **Type**: *bool* (`true` or `1`) -**Default**: false +**Default**: `false` **Set using**: `UseSetting` **Environment variable**: `ASPNETCORE_PREVENTHOSTINGSTARTUP` @@ -1827,14 +300,14 @@ Indicates the IP addresses or host addresses with ports and protocols that the s **Set using**: `UseUrls` **Environment variable**: `ASPNETCORE_URLS` -Set to a semicolon-separated (;) list of URL prefixes to which the server should respond. For example, `http://localhost:123`. 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`). The protocol (`http://` or `https://`) must be included with each URL. Supported formats vary among servers. +Set to a semicolon-separated `;` list of URL prefixes to which the server should respond. For example, `http://localhost:123`. Use a wildcard asterisk `*` to indicate that the server should listen for requests on any IP address or hostname by using the specified port and protocol (for example, `http://*:5000`). The protocol (`http://` or `https://`) must be included with each URL. Supported formats vary among servers. ```csharp WebHost.CreateDefaultBuilder(args) .UseUrls("http://*:5000;http://localhost:5001;https://hostname:5002") ``` -Kestrel has its own endpoint configuration API. For more information, see . +Kestrel has its own endpoint configuration API. For more information, see . ### Shutdown Timeout @@ -1846,14 +319,14 @@ Specifies the amount of time to wait for Web Host to shut down. **Set using**: `UseShutdownTimeout` **Environment variable**: `ASPNETCORE_SHUTDOWNTIMEOUTSECONDS` -Although the key accepts an *int* with `UseSetting` (for example, `.UseSetting(WebHostDefaults.ShutdownTimeoutKey, "10")`), the extension method takes a . +Although the key accepts an *int* with `UseSetting` (for example, `.UseSetting(WebHostDefaults.ShutdownTimeoutKey, "10")`), the extension method takes a parameter. During the timeout period, hosting: -* Triggers . +* Triggers . * 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. +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 aren't finished processing. If services require more time to stop, increase the timeout. ```csharp WebHost.CreateDefaultBuilder(args) @@ -1866,11 +339,11 @@ Determines the assembly to search for the `Startup` class. **Key**: startupAssembly **Type**: *string* -**Default**: The app's assembly +**Default**: The application assembly **Set using**: `UseStartup` **Environment variable**: `ASPNETCORE_STARTUPASSEMBLY` -The assembly by name (`string`) or type (`TStartup`) can be referenced. If multiple `UseStartup` methods are called, the last one takes precedence. +The assembly by name (`string`) or type (`TStartup`) can be referenced. If multiple `UseStartup` methods are called, the last call takes precedence. ```csharp WebHost.CreateDefaultBuilder(args) @@ -1888,7 +361,7 @@ Sets the relative path to the app's static assets. **Key**: webroot **Type**: *string* -**Default**: The default is `wwwroot`. The path to *{content root}/wwwroot* must exist. If the path doesn't exist, a no-op file provider is used. +**Default**: The default is `wwwroot`. The path to `{content root}/wwwroot` must exist. If the path doesn't exist, a no-op file provider is used. **Set using**: `UseWebRoot` **Environment variable**: `ASPNETCORE_WEBROOT` @@ -1902,11 +375,13 @@ For more information, see: * [Fundamentals: Web root](xref:fundamentals/index#web-root) * [Content root](#content-root) -## Override configuration +## Override the Web Host configuration + +Use application [configuration in ASP.NET Core](xref:fundamentals/configuration/index) to configure the Web Host. -Use [Configuration](xref:fundamentals/configuration/index) to configure Web Host. In the following example, host configuration is optionally specified in a `hostsettings.json` file. Any configuration loaded from the `hostsettings.json` file may be overridden by command-line arguments. The built configuration (in `config`) is used to configure the host with . `IWebHostBuilder` configuration is added to the app's configuration, but the converse isn't true—`ConfigureAppConfiguration` doesn't affect the `IWebHostBuilder` configuration. +In the following example, host configuration is optionally specified in a _hostsettings.json_ file. Command-line arguments can override any configuration loaded from the _hostsettings.json_ file. The built configuration (in config) is used to configure the host with the method. `IWebHostBuilder` configuration is added to the application configuration, but the converse isn't true. The `ConfigureAppConfiguration` method doesn't affect the `IWebHostBuilder` configuration. -Overriding the configuration provided by `UseUrls` with `hostsettings.json` config first, command-line argument config second: +Overriding the configuration provided by `UseUrls` with the _hostsettings.json_ config followed by the command-line argument config: ```csharp public class Program @@ -1936,7 +411,7 @@ public class Program } ``` -`hostsettings.json`: +The _hostsettings.json_ file contents: ```json { @@ -1945,17 +420,19 @@ public class Program ``` > [!NOTE] -> only copies keys from the provided `IConfiguration` to the host builder configuration. Therefore, setting `reloadOnChange: true` for JSON, INI, and XML settings files has no effect. +> The method only copies keys from the provided `IConfiguration` to the host builder configuration. Therefore, setting the `reloadOnChange: true` property for JSON, INI, and XML settings files have no effect. -To specify the host run on a particular URL, the desired value can be passed in from a command prompt when executing [dotnet run](/dotnet/core/tools/dotnet-run). The command-line argument overrides the `urls` value from the `hostsettings.json` file, and the server listens on port 8080: +To specify the host run on a particular URL, the desired value can be passed in from a command prompt when executing [dotnet run](/dotnet/core/tools/dotnet-run). The command-line argument overrides the `urls` value from the _hostsettings.json_ file, and the server listens on port 8080: ```dotnetcli dotnet run --urls "http://*:8080" ``` -## Manage the host +## Manage the Web Host -**Run** +To manage the Web Host, you use the following methods. + +### Run The `Run` method starts the web app and blocks the calling thread until the host is shut down: @@ -1963,9 +440,9 @@ The `Run` method starts the web app and blocks the calling thread until the host host.Run(); ``` -**Start** +### Start -Run the host in a non-blocking manner by calling its `Start` method: +Run the host in a nonblocking manner by calling its `Start` method: ```csharp using (host) @@ -1995,11 +472,11 @@ using (host) } ``` -The app can initialize and start a new host using the pre-configured defaults of `CreateDefaultBuilder` using a static convenience method. These methods start the server without console output and with wait for a break (Ctrl-C/SIGINT or SIGTERM): +The app can initialize and start a new host with the preconfigured defaults of the `CreateDefaultBuilder` method by using a static convenience method. These methods start the server without console output and use the method, which waits for a break (Ctrl-C/SIGINT or SIGTERM). -**Start(RequestDelegate app)** +### Start(RequestDelegate app) -Start with a `RequestDelegate`: +Run the host by starting with a `RequestDelegate`: parameter ```csharp using (var host = WebHost.Start(app => app.Response.WriteAsync("Hello, World!"))) @@ -2009,11 +486,11 @@ using (var host = WebHost.Start(app => app.Response.WriteAsync("Hello, World!")) } ``` -Make a request in the browser to `http://localhost:5000` to receive the response "Hello World!" `WaitForShutdown` blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. +Make a request in the browser to the `http://localhost:5000` URL to receive the response "Hello World!" The `WaitForShutdown` method blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. -**Start(string url, RequestDelegate app)** +### Start(string url, RequestDelegate app) -Start with a URL and `RequestDelegate`: +Run the host by starting with a URL and the `RequestDelegate` parameter: ```csharp using (var host = WebHost.Start("http://localhost:8080", app => app.Response.WriteAsync("Hello, World!"))) @@ -2023,11 +500,11 @@ using (var host = WebHost.Start("http://localhost:8080", app => app.Response.Wri } ``` -Produces the same result as **Start(RequestDelegate app)**, except the app responds on `http://localhost:8080`. +Produces the same result as **Start(RequestDelegate app)**, except the app responds on the `http://localhost:8080` URL. -**Start(Action\ routeBuilder)** +### Start(Action\ routeBuilder) -Use an instance of `IRouteBuilder` ([Microsoft.AspNetCore.Routing](https://www.nuget.org/packages/Microsoft.AspNetCore.Routing/)) to use routing middleware: +Run the host by starting with an instance of `IRouteBuilder` ([Microsoft.AspNetCore.Routing](https://www.nuget.org/packages/Microsoft.AspNetCore.Routing/)), which uses routing middleware: ```csharp using (var host = WebHost.Start(router => router @@ -2052,16 +529,16 @@ Use the following browser requests with the example: |--|--| | `http://localhost:5000/hello/Martin` | Hello, Martin! | | `http://localhost:5000/buenosdias/Catrina` | Buenos dias, Catrina! | -| `http://localhost:5000/throw/ooops!` | Throws an exception with string "ooops!" | +| `http://localhost:5000/throw/ooops!` | Throws an exception with string "oops!" | | `http://localhost:5000/throw` | Throws an exception with string "Uh oh!" | | `http://localhost:5000/Sante/Kevin` | Sante, Kevin! | | `http://localhost:5000` | Hello World! | -`WaitForShutdown` blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. +The `WaitForShutdown` method blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. -**Start(string url, Action\ routeBuilder)** +### Start(string url, Action\ routeBuilder) -Use a URL and an instance of `IRouteBuilder`: +Run the host by starting with a URL and an instance of `IRouteBuilder`: ```csharp using (var host = WebHost.Start("http://localhost:8080", router => router @@ -2080,11 +557,11 @@ using (var host = WebHost.Start("http://localhost:8080", router => router } ``` -Produces the same result as **Start(Action\ routeBuilder)**, except the app responds at `http://localhost:8080`. +Produces the same result as [Start(Action\ routeBuilder)](#startactioniroutebuilder-routebuilder), except the app responds on the `http://localhost:8080` URL. -**StartWith(Action\ app)** +### StartWith(Action\ app) -Provide a delegate to configure an `IApplicationBuilder`: +Run the host by starting with a delegate that configures an `IApplicationBuilder`: ```csharp using (var host = WebHost.StartWith(app => @@ -2101,11 +578,11 @@ using (var host = WebHost.StartWith(app => } ``` -Make a request in the browser to `http://localhost:5000` to receive the response "Hello World!" `WaitForShutdown` blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. +Make a request in the browser to the `http://localhost:5000` URL to receive the response "Hello World!" The `WaitForShutdown` method blocks until a break (Ctrl-C/SIGINT or SIGTERM) is issued. The app displays the `Console.WriteLine` message and waits for a keypress to exit. -**StartWith(string url, Action\ app)** +### StartWith(string url, Action\ app) -Provide a URL and a delegate to configure an `IApplicationBuilder`: +Run the host by starting with a URL and a delegate that configures an `IApplicationBuilder`: ```csharp using (var host = WebHost.StartWith("http://localhost:8080", app => @@ -2122,11 +599,11 @@ using (var host = WebHost.StartWith("http://localhost:8080", app => } ``` -Produces the same result as **StartWith(Action\ app)**, except the app responds on `http://localhost:8080`. +Produces the same result as [StartWith(Action\ app)](#startwithactioniapplicationbuilder-app), except the app responds on the `http://localhost:8080` URL. -## IWebHostEnvironment interface +## Use the IWebHostEnvironment interface -The `IWebHostEnvironment` interface provides information about the app's web hosting environment. Use [constructor injection](xref:fundamentals/dependency-injection) to obtain the `IWebHostEnvironment` in order to use its properties and extension methods: +The `IWebHostEnvironment` interface provides information about the app's web hosting environment. Use [constructor injection](xref:fundamentals/dependency-injection) to obtain the `IWebHostEnvironment` instance, and then access its properties and extension methods: ```csharp public class CustomFileReader @@ -2146,7 +623,7 @@ public class CustomFileReader } ``` -A [convention-based approach](xref:fundamentals/environments#environment-based-startup-class-and-methods) can be used to configure the app at startup based on the environment. Alternatively, inject the `IWebHostEnvironment` into the `Startup` constructor for use in `ConfigureServices`: +A [convention-based approach](xref:fundamentals/environments#environment-based-startup-class-and-methods) can be used to configure the app at startup based on the environment. Alternatively, inject the `IWebHostEnvironment` instance into the `Startup` constructor for use in the `ConfigureServices` method: ```csharp public class Startup @@ -2175,7 +652,7 @@ public class Startup ``` > [!NOTE] -> In addition to the `IsDevelopment` extension method, `IWebHostEnvironment` offers `IsStaging`, `IsProduction`, and `IsEnvironment(string environmentName)` methods. For more information, see . +> In addition to the `IsDevelopment` extension method, `IWebHostEnvironment` offers the `IsStaging`, `IsProduction`, and `IsEnvironment(string environmentName)` methods. For more information, see . The `IWebHostEnvironment` service can also be injected directly into the `Configure` method for setting up the processing pipeline: @@ -2215,15 +692,15 @@ public async Task Invoke(HttpContext context, IWebHostEnvironment env) } ``` -## IHostApplicationLifetime interface +## Use the IHostApplicationLifetime interface `IHostApplicationLifetime` allows for post-startup and shutdown activities. Three properties on the interface are cancellation tokens used to register `Action` methods that define startup and shutdown events. -| Cancellation Token | Triggered when… | +| Cancellation token | Trigger | |--|--| -| `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. | +| `ApplicationStarted` | The host is fully started. | +| `ApplicationStopped` | The host is completing a graceful shutdown. All requests are expected to process. Shutdown blocks until this event completes. | +| `ApplicationStopping` | The host is performing a graceful shutdown. Requests might still be in process. Shutdown blocks until this event completes. | ```csharp public class Startup @@ -2259,7 +736,7 @@ public class Startup } ``` -`StopApplication` requests termination of the app. The following class uses `StopApplication` to gracefully shut down an app when the class's `Shutdown` method is called: +The `StopApplication` method requests termination of the app. The following class uses `StopApplication` to gracefully shut down an app when the class's `Shutdown` method is called: ```csharp public class MyClass @@ -2278,20 +755,20 @@ public class MyClass } ``` -## Scope validation +## Configure scope validation - sets to `true` if the app's environment is `Development`. +The method sets the property to `true` if the app's environment is `Development`. -When `ValidateScopes` is set to `true`, the default service provider performs checks to verify that: +When `ValidateScopes` is set to `true`, the default service provider performs checks to verify: * Scoped services aren't directly or indirectly resolved from the root service provider. * Scoped services aren't directly or indirectly injected into singletons. -The root service provider is created when 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. +The root service provider is created when the method 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. Validating service scopes catches these situations when `BuildServiceProvider` is called. +The container that created the scoped services also disposes the services. If a scoped service is created in the root container, the service's lifetime is effectively promoted to singleton. The root container disposes the service only when the app/server is shut down. Validating service scopes catches these situations when `BuildServiceProvider` is called. -To always validate scopes, including in the `Production` environment, configure the with on the host builder: +To always validate scopes, including in the `Production` environment, configure the object with the method on the host builder: ```csharp WebHost.CreateDefaultBuilder(args) @@ -2300,10 +777,8 @@ WebHost.CreateDefaultBuilder(args) }) ``` -## Additional resources +## Related content * * -* - -:::moniker-end +* \ No newline at end of file