aspnetcore/fundamentals/index.md
:::moniker range=">= aspnetcore-9.0"
This article provides an overview of the fundamentals for building ASP.NET Core apps, including dependency injection (DI), configuration, middleware, and more.
For Blazor fundamentals guidance, which adds to or supersedes the guidance in this article, see xref:blazor/fundamentals/index.
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 several app types:
ASP.NET Core features built-in 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 automatically. builder is a WebApplicationBuilder in the following code:
:::code language="csharp" source="~/fundamentals/startup/6.0_samples/WebAll/Program.cs" id="snippet2":::
In the preceding code, CreateBuilder adds configuration, logging, and many other services to the DI container. The DI framework provides an instance of a requested service at run time.
The following code adds a custom xref:Microsoft.EntityFrameworkCore.DbContext and Blazor components to the DI container:
:::code language="csharp" source="~/fundamentals/index/samples/9.0/BlazorWebAppMovies/Program.cs" id="snippet_services" highlight="2-4,11-12":::
In Blazor Web Apps, services are often resolved from DI at run time by using the @inject directive in a Razor component, as shown in the following example:
:::code language="razor" source="~/fundamentals/index/samples/9.0/BlazorWebAppMovies/Components/Pages/MoviePages/Index.razor" highlight ="8,44,48":::
In the preceding code:
@inject directive is used.OnInitialized method and assigned to the context variable.context service creates the FilteredMovie list.Another way to resolve a service from DI is by using constructor injection. The following Razor Pages code uses constructor injection to resolve the database context and a logger from DI:
:::code language="csharp" source="~/fundamentals/index/samples/6.0/RazorPagesMovie/Pages/Movies/Index.cshtml.cs" id="snippet":::
In the preceding code, the IndexModel constructor takes a parameter of type RazorPagesMovieContext, which is resolved at run time into the _context variable. The context object is used to create a list of movies in the OnGetAsync method.
For more information, see xref:blazor/fundamentals/dependency-injection and 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{Feature} extension method. The use of methods named Use{Feature} to add middleware to an app is illustrated in the following code:
:::code language="csharp" source="~/fundamentals/index/samples/9.0/BlazorWebAppMovies/Program.cs" id="snippet_middleware" highlight="26-28,30,32":::
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 are 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 fewer callbacks to configure. The ASP.NET Core xref:Microsoft.AspNetCore.WebHost is available only for backward compatibility.
The following example instantiates a WebApplication and assigns it to a variable named app:
:::code language="csharp" source="~/fundamentals/index/samples/9.0/BlazorWebAppMovies/Program.cs" id="snippet_services" highlight="1,14":::
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 enables 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 xref:Microsoft.AspNetCore.Http.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 in the Development environment, .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:
:::code language="csharp" source="~/fundamentals/index/samples/9.0/BlazorWebAppMovies/Program.cs" id="snippet_environments" highlight="1":::
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. The following example shows how to get and use a logger in a .razor file for a page in a Blazor Web App. A logger object and a console provider for it are stored in the DI container automatically when the xref:Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder%2A method is called in Program.cs.
:::code language="csharp" source="~/fundamentals/index/samples/9.0/BlazorWebAppMovies/Components/Pages/Weather.razor" highlight="3,49-51":::
For more information, see xref:fundamentals/logging/index.
Routing in ASP.NET Core is a mechanism that maps incoming requests to specific endpoints in an application. It enables you to define URL patterns that correspond to different components, such as Razor components, Razor pages, MVC controller actions, or middleware.
The xref:Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseRouting%2A method adds routing middleware to the request pipeline. This middleware processes the routing information and determines the appropriate endpoint for each request. You don't have to explicitly call UseRouting unless you want to change the order in which middleware is processed.
For more information, see xref:fundamentals/routing and xref:blazor/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 xref:System.Net.Http.IHttpClientFactory is available for creating xref:System.Net.Http.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.HttpClient lifetimes manually.For more information, see xref:fundamentals/http-requests.
The content root is the base path for:
.cshtml, .razor).json, .xml).db)wwwroot folder.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, where the {CONTENT ROOT} placeholder is the content root. 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.
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.
xref:blazor/fundamentals/index
:::moniker-end