aspnetcore/fundamentals/index/includes/index3-7.md
:::moniker range=">= aspnetcore-6.0 < aspnetcore-8.0"
This article provides an overview of the fundamentals for building ASP.NET Core apps, including dependency injection (DI), configuration, middleware, and more.
ASP.NET Core apps created with the web templates contain the application startup code in the Program.cs file. The Program.cs file is where:
The following app startup code supports:
ASP.NET Core includes dependency injection (DI) that makes configured services available throughout an app. Services are added to the DI container with WebApplicationBuilder.Services, builder.Services in the preceding code. When the xref:Microsoft.AspNetCore.Builder.WebApplicationBuilder is instantiated, many framework-provided services are added. builder is a WebApplicationBuilder in the following code:
In the preceding highlighted code, builder has configuration, logging, and many other services added to the DI container.
The following code adds Razor Pages, MVC controllers with views, and a custom xref:Microsoft.EntityFrameworkCore.DbContext to the DI container:
Services are typically resolved from DI using constructor injection. The DI framework provides an instance of this service at runtime.
The following code uses constructor injection to resolve the database context and logger from DI:
[!code-csharp[](~/fundamentals/index/samples/6.0/RazorPagesMovie/Pages/Movies/Index.cshtml.cs?name=snippet&highlight=3-10, 16-17)]
The request handling pipeline is composed as a series of middleware components. Each component performs operations on an HttpContext and either invokes the next middleware in the pipeline or terminates the request.
By convention, a middleware component is added to the pipeline by invoking a Use{Feature} extension method. Middleware added to the app is highlighted in the following code:
For more information, see xref:fundamentals/middleware/index.
On startup, an ASP.NET Core app builds a host. The host encapsulates all of the app's resources, such as:
There are three different hosts capable of running an ASP.NET Core app:
The ASP.NET Core xref:Microsoft.AspNetCore.Builder.WebApplication and xref:Microsoft.AspNetCore.Builder.WebApplicationBuilder types are recommended and used in all the ASP.NET Core templates. WebApplication behaves similarly to the .NET Generic Host and exposes many of the same interfaces but requires less callbacks to configure. The ASP.NET Core xref:Microsoft.AspNetCore.WebHost is available only for backward compatibility.
The following example instantiates a WebApplication:
The WebApplicationBuilder.Build method configures a host with a set of default options, such as:
appsettings.json, environment variables, command line arguments, and other configuration sources.The Generic Host allows other types of apps to use cross-cutting framework extensions, such as logging, dependency injection (DI), configuration, and app lifetime management. For more information, see xref:fundamentals/host/generic-host and xref:fundamentals/host/hosted-services.
An ASP.NET Core app uses an HTTP server implementation to listen for HTTP requests. The server surfaces requests to the app as a set of request features composed into an HttpContext.
ASP.NET Core provides the following server implementations:
ASP.NET Core provides the Kestrel cross-platform server implementation. In ASP.NET Core 2.0 or later, Kestrel can run as a public-facing edge server exposed directly to the Internet. Kestrel is often run in a reverse proxy configuration with Nginx or Apache.
ASP.NET Core provides the Kestrel cross-platform server implementation. In ASP.NET Core 2.0 or later, Kestrel can run as a public-facing edge server exposed directly to the Internet. Kestrel is often run in a reverse proxy configuration with Nginx or Apache.
For more information, see xref:fundamentals/servers/index.
ASP.NET Core provides a configuration framework that gets settings as name-value pairs from an ordered set of configuration providers. Built-in configuration providers are available for a variety of sources, such as .json files, .xml files, environment variables, and command-line arguments. Write custom configuration providers to support other sources.
By default, ASP.NET Core apps are configured to read from appsettings.json, environment variables, the command line, and more. When the app's configuration is loaded, values from environment variables override values from appsettings.json.
For managing confidential configuration data such as passwords, .NET provides the Secret Manager. For production secrets, we recommend Azure Key Vault.
For more information, see xref:fundamentals/configuration/index.
Execution environments, such as Development, Staging, and Production, are available in ASP.NET Core. Specify the environment an app is running in by setting the ASPNETCORE_ENVIRONMENT environment variable. ASP.NET Core reads that environment variable at app startup and stores the value in an IWebHostEnvironment implementation. This implementation is available anywhere in an app via dependency injection (DI).
The following example configures the exception handler and HTTP Strict Transport Security Protocol (HSTS) middleware when not running in the Development environment:
For more information, see xref:fundamentals/environments.
ASP.NET Core supports a logging API that works with a variety of built-in and third-party logging providers. Available providers include:
To create logs, resolve an xref:Microsoft.Extensions.Logging.ILogger%601 service from dependency injection (DI) and call logging methods such as xref:Microsoft.Extensions.Logging.LoggerExtensions.LogInformation%2A. For example:
[!code-csharp[](~/fundamentals/index/samples/6.0/RazorPagesMovie/Pages/Movies/Index.cshtml.cs?name=snippet&highlight=3-10, 16-17)]
For more information, see xref:fundamentals/logging/index.
A route is a URL pattern that is mapped to a handler. The handler is typically a Razor page, an action method in an MVC controller, or a middleware. ASP.NET Core routing gives you control over the URLs used by your app.
The following code, generated by the ASP.NET Core web application template, calls xref:Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseRouting%2A:
For more information, see xref:fundamentals/routing.
ASP.NET Core has built-in features for handling errors, such as:
For more information, see xref:fundamentals/error-handling.
An implementation of IHttpClientFactory is available for creating HttpClient instances. The factory:
HttpClient instances. For example, register and configure a github client for accessing GitHub. Register and configure a default client for other purposes.HttpClientHandler instances to avoid common DNS problems that occur when managing HttpClient lifetimes manually.For more information, see xref:fundamentals/http-requests.
The content root is the base path for:
.cshtml, .razor).json, .xml).db)During development, the content root defaults to the project's root directory. This directory is also the base path for both the app's content files and the Web root. Specify a different content root by setting its path when building the host. For more information, see Content root.
The web root is the base path for public, static resource files, such as:
.css).js).png, .jpg)By default, static files are served only from the web root directory and its sub-directories. The web root path defaults to {content root}/wwwroot. Specify a different web root by setting its path when building the host. For more information, see Web root.
Prevent publishing files in wwwroot with the <Content> project item in the project file. The following example prevents publishing content in wwwroot/local and its sub-directories:
<ItemGroup>
<Content Update="wwwroot\local\**\*.*" CopyToPublishDirectory="Never" />
</ItemGroup>
In Razor .cshtml files, ~/ points to the web root. A path beginning with ~/ is referred to as a virtual path.
For more information, see xref:fundamentals/static-files.
:::moniker-end
:::moniker range="< aspnetcore-6.0"
This article provides an overview of the fundamentals for building ASP.NET Core apps, including dependency injection (DI), configuration, middleware, and more.
The Startup class is where:
Here's a sample Startup class:
For more information, see xref:fundamentals/startup.
ASP.NET Core includes a built-in dependency injection (DI) framework that makes configured services available throughout an app. For example, a logging component is a service.
Code to configure (or register) services is added to the Startup.ConfigureServices method. For example:
Services are typically resolved from DI using constructor injection. With constructor injection, a class declares a constructor parameter of either the required type or an interface. The DI framework provides an instance of this service at runtime.
The following example uses constructor injection to resolve a RazorPagesMovieContext from DI:
If the built-in Inversion of Control (IoC) container doesn't meet all of an app's needs, a third-party IoC container can be used instead.
For more information, see xref:fundamentals/dependency-injection.
The request handling pipeline is composed as a series of middleware components. Each component performs operations on an HttpContext and either invokes the next middleware in the pipeline or terminates the request.
By convention, a middleware component is added to the pipeline by invoking a Use... extension method in the Startup.Configure method. For example, to enable rendering of static files, call UseStaticFiles.
The following example configures a request handling pipeline:
ASP.NET Core includes a rich set of built-in middleware. Custom middleware components can also be written.
For more information, see xref:fundamentals/middleware/index.
On startup, an ASP.NET Core app builds a host. The host encapsulates all of the app's resources, such as:
There are two different hosts:
The .NET Generic Host is recommended. The ASP.NET Core Web Host is available only for backwards compatibility.
The following example creates a .NET Generic Host:
The CreateDefaultBuilder and ConfigureWebHostDefaults methods configure a host with a set of default options, such as:
appsettings.json, appsettings.{Environment}.json, environment variables, command line arguments, and other configuration sources.For more information, see xref:fundamentals/host/generic-host.
The Generic Host allows other types of apps to use cross-cutting framework extensions, such as logging, dependency injection (DI), configuration, and app lifetime management. For more information, see xref:fundamentals/host/generic-host and xref:fundamentals/host/hosted-services.
An ASP.NET Core app uses an HTTP server implementation to listen for HTTP requests. The server surfaces requests to the app as a set of request features composed into an HttpContext.
ASP.NET Core provides the following server implementations:
ASP.NET Core provides the Kestrel cross-platform server implementation. In ASP.NET Core 2.0 or later, Kestrel can run as a public-facing edge server exposed directly to the Internet. Kestrel is often run in a reverse proxy configuration with Nginx or Apache.
ASP.NET Core provides the Kestrel cross-platform server implementation. In ASP.NET Core 2.0 or later, Kestrel can run as a public-facing edge server exposed directly to the Internet. Kestrel is often run in a reverse proxy configuration with Nginx or Apache.
For more information, see xref:fundamentals/servers/index.
ASP.NET Core provides a configuration framework that gets settings as name-value pairs from an ordered set of configuration providers. Built-in configuration providers are available for a variety of sources, such as .json files, .xml files, environment variables, and command-line arguments. Write custom configuration providers to support other sources.
By default, ASP.NET Core apps are configured to read from appsettings.json, environment variables, the command line, and more. When the app's configuration is loaded, values from environment variables override values from appsettings.json.
The preferred way to read related configuration values is using the options pattern.
For managing confidential configuration data such as passwords, .NET provides the Secret Manager. For production secrets, we recommend Azure Key Vault.
For more information, see xref:fundamentals/configuration/index.
Execution environments, such as Development, Staging, and Production, are a first-class notion in ASP.NET Core. Specify the environment an app is running in by setting the ASPNETCORE_ENVIRONMENT environment variable. ASP.NET Core reads that environment variable at app startup and stores the value in an IWebHostEnvironment implementation. This implementation is available anywhere in an app via dependency injection (DI).
The following example configures the app to provide detailed error information when running in the Development environment:
For more information, see xref:fundamentals/environments.
ASP.NET Core supports a logging API that works with a variety of built-in and third-party logging providers. Available providers include:
To create logs, resolve an xref:Microsoft.Extensions.Logging.ILogger%601 service from dependency injection (DI) and call logging methods such as xref:Microsoft.Extensions.Logging.LoggerExtensions.LogInformation%2A. For example:
Logging methods such as LogInformation support any number of fields. These fields are commonly used to construct a message string, but some logging providers send these to a data store as separate fields. This feature makes it possible for logging providers to implement semantic logging, also known as structured logging.
For more information, see xref:fundamentals/logging/index.
A route is a URL pattern that is mapped to a handler. The handler is typically a Razor page, an action method in an MVC controller, or a middleware. ASP.NET Core routing gives you control over the URLs used by your app.
For more information, see xref:fundamentals/routing.
ASP.NET Core has built-in features for handling errors, such as:
For more information, see xref:fundamentals/error-handling.
An implementation of IHttpClientFactory is available for creating HttpClient instances. The factory:
HttpClient instances. For example, register and configure a github client for accessing GitHub. Register and configure a default client for other purposes.HttpClientHandler instances to avoid common DNS problems that occur when managing HttpClient lifetimes manually.For more information, see xref:fundamentals/http-requests.
The content root is the base path for:
.cshtml, .razor).json, .xml).db)During development, the content root defaults to the project's root directory. This directory is also the base path for both the app's content files and the Web root. Specify a different content root by setting its path when building the host. For more information, see Content root.
The web root is the base path for public, static resource files, such as:
.css).js).png, .jpg)By default, static files are served only from the web root directory and its sub-directories. The web root path defaults to {content root}/wwwroot. Specify a different web root by setting its path when building the host. For more information, see Web root.
Prevent publishing files in wwwroot with the <Content> project item in the project file. The following example prevents publishing content in wwwroot/local and its sub-directories:
<ItemGroup>
<Content Update="wwwroot\local\**\*.*" CopyToPublishDirectory="Never" />
</ItemGroup>
In Razor .cshtml files, tilde-slash (~/) points to the web root. A path beginning with ~/ is referred to as a virtual path.
For more information, see xref:fundamentals/static-files.
Many of the articles and tutorials include links to sample code.
AspNetCore.Docs-main.zip file.To demonstrate multiple scenarios, sample apps use the #define and #if-#else/#elif-#endif preprocessor directives to selectively compile and run different sections of sample code. For those samples that make use of this approach, set the #define directive at the top of the C# files to define the symbol associated with the scenario that you want to run. Some samples require defining the symbol at the top of multiple files in order to run a scenario.
For example, the following #define symbol list indicates that four scenarios are available (one scenario per symbol). The current sample configuration runs the TemplateCode scenario:
#define TemplateCode // or LogFromMain or ExpandDefault or FilterInCode
To change the sample to run the ExpandDefault scenario, define the ExpandDefault symbol and leave the remaining symbols commented-out:
#define ExpandDefault // TemplateCode or LogFromMain or FilterInCode
For more information on using C# preprocessor directives to selectively compile sections of code, see #define (C# Reference) and #if (C# Reference).
Some sample apps contain sections of code surrounded by #region and #endregion C# directives. The documentation build system injects these regions into the rendered documentation topics.
Region names usually contain the word "snippet." The following example shows a region named snippet_WebHostDefaults:
#region snippet_WebHostDefaults
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
#endregion
The preceding C# code snippet is referenced in the topic's markdown file with the following line:
[!code-csharp[](sample/SampleApp/Program.cs?name=snippet_WebHostDefaults)]
You may safely ignore or remove the #region and #endregion directives that surround the code. Don't alter the code within these directives if you plan to run the sample scenarios described in the topic.
For more information, see Contribute to the ASP.NET documentation: Code snippets.
:::moniker-end