|
| 1 | +:::moniker range="= aspnetcore-8.0" |
| 2 | + |
| 3 | +This article provides an overview of the fundamentals for building ASP.NET Core apps, including dependency injection (DI), configuration, middleware, and more. |
| 4 | + |
| 5 | +For Blazor fundamentals guidance, which adds to or supersedes the guidance in this node, see <xref:blazor/fundamentals/index>. |
| 6 | + |
| 7 | +## Program.cs |
| 8 | + |
| 9 | +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: |
| 10 | + |
| 11 | +* Services required by the app are configured. |
| 12 | +* The app's request handling pipeline is defined as a series of [middleware components](xref:fundamentals/middleware/index). |
| 13 | + |
| 14 | +The following app startup code supports: |
| 15 | + |
| 16 | +* [Razor Pages](xref:tutorials/razor-pages/razor-pages-start) |
| 17 | +* [MVC controllers with views](xref:tutorials/first-mvc-app/start-mvc) |
| 18 | +* [Web API with controllers](xref:tutorials/first-web-api) |
| 19 | +* [Minimal web APIs](xref:tutorials/min-web-api) |
| 20 | + |
| 21 | +[!code-csharp[](~/fundamentals/startup/6.0_samples/WebAll/Program.cs?name=snippet)] |
| 22 | + |
| 23 | +## Dependency injection (services) |
| 24 | + |
| 25 | +ASP.NET Core includes [dependency injection (DI)](xref:fundamentals/dependency-injection) that makes configured services available throughout an app. Services are added to the DI container with [WebApplicationBuilder.Services](xref:Microsoft.AspNetCore.Builder.WebApplicationBuilder.Services), `builder.Services` in the preceding code. When the <xref:Microsoft.AspNetCore.Builder.WebApplicationBuilder> is instantiated, many [framework-provided services](xref:fundamentals/dependency-injection#framework-provided-services) are added. `builder` is a `WebApplicationBuilder` in the following code: |
| 26 | + |
| 27 | +[!code-csharp[](~/fundamentals/startup/6.0_samples/WebAll/Program.cs?name=snippet2&highlight=1)] |
| 28 | + |
| 29 | +In the preceding highlighted code, `builder` has configuration, logging, and [many other services](xref:fundamentals/dependency-injection#framework-provided-services) added to the DI container. |
| 30 | + |
| 31 | +The following code adds Razor Pages, MVC controllers with views, and a custom <xref:Microsoft.EntityFrameworkCore.DbContext> to the DI container: |
| 32 | + |
| 33 | +[!code-csharp[](~/fundamentals/index/samples/6.0/RazorPagesMovie/Program.cs?name=snippet2&highlight=6-10)] |
| 34 | + |
| 35 | +Services are typically resolved from DI using constructor injection. The DI framework provides an instance of this service at runtime. |
| 36 | + |
| 37 | +The following code uses constructor injection to resolve the database context and logger from DI: |
| 38 | + |
| 39 | +[!code-csharp[](~/fundamentals/index/samples/6.0/RazorPagesMovie/Pages/Movies/Index.cshtml.cs?name=snippet&highlight=3-10, 16-17)] |
| 40 | + |
| 41 | +## Middleware |
| 42 | + |
| 43 | +The request handling pipeline is composed as a series of middleware components. Each component performs operations on an [`HttpContext`](xref:fundamentals/httpcontext) and either invokes the next middleware in the pipeline or terminates the request. |
| 44 | + |
| 45 | +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: |
| 46 | + |
| 47 | +[!code-csharp[](~/fundamentals/startup/6.0_samples/WebAll/Program.cs?name=snippet&highlight=12-19)] |
| 48 | + |
| 49 | +For more information, see <xref:fundamentals/middleware/index>. |
| 50 | + |
| 51 | +## Host |
| 52 | + |
| 53 | +On startup, an ASP.NET Core app builds a *host*. The host encapsulates all of the app's resources, such as: |
| 54 | + |
| 55 | +* An HTTP server implementation |
| 56 | +* Middleware components |
| 57 | +* Logging |
| 58 | +* Dependency injection (DI) services |
| 59 | +* Configuration |
| 60 | + |
| 61 | +There are three different hosts capable of running an ASP.NET Core app: |
| 62 | + |
| 63 | +* [ASP.NET Core WebApplication](xref:fundamentals/minimal-apis/webapplication), also known as the [Minimal Host](xref:migration/50-to-60#new-hosting-model) |
| 64 | +* [.NET Generic Host](xref:fundamentals/host/generic-host) combined with ASP.NET Core's <xref:Microsoft.Extensions.Hosting.GenericHostBuilderExtensions.ConfigureWebHostDefaults%2A> |
| 65 | +* [ASP.NET Core WebHost](xref:fundamentals/host/web-host) |
| 66 | + |
| 67 | +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. |
| 68 | + |
| 69 | +The following example instantiates a `WebApplication`: |
| 70 | + |
| 71 | +[!code-csharp[](~/fundamentals/startup/6.0_samples/WebAll/Program.cs?name=snippet2&highlight=7)] |
| 72 | + |
| 73 | +The [WebApplicationBuilder.Build](xref:Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build%2A) method configures a host with a set of default options, such as: |
| 74 | + |
| 75 | +* Use [Kestrel](#servers) as the web server and enable IIS integration. |
| 76 | +* Load [configuration](xref:fundamentals/configuration/index) from `appsettings.json`, environment variables, command line arguments, and other configuration sources. |
| 77 | +* Send logging output to the console and debug providers. |
| 78 | + |
| 79 | +### Non-web scenarios |
| 80 | + |
| 81 | +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>. |
| 82 | + |
| 83 | +## Servers |
| 84 | + |
| 85 | +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](xref:fundamentals/request-features) composed into an `HttpContext`. |
| 86 | + |
| 87 | +# [Windows](#tab/windows) |
| 88 | + |
| 89 | +ASP.NET Core provides the following server implementations: |
| 90 | + |
| 91 | +* *Kestrel* is a cross-platform web server. Kestrel is often run in a reverse proxy configuration using [IIS](https://www.iis.net/). In ASP.NET Core 2.0 or later, Kestrel can be run as a public-facing edge server exposed directly to the Internet. |
| 92 | +* *IIS HTTP Server* is a server for Windows that uses IIS. With this server, the ASP.NET Core app and IIS run in the same process. |
| 93 | +* *HTTP.sys* is a server for Windows that isn't used with IIS. |
| 94 | + |
| 95 | +# [macOS](#tab/macos) |
| 96 | + |
| 97 | +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](https://nginx.org) or [Apache](https://httpd.apache.org/). |
| 98 | + |
| 99 | +# [Linux](#tab/linux) |
| 100 | + |
| 101 | +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](https://nginx.org) or [Apache](https://httpd.apache.org/). |
| 102 | + |
| 103 | +--- |
| 104 | + |
| 105 | +For more information, see <xref:fundamentals/servers/index>. |
| 106 | + |
| 107 | +## Configuration |
| 108 | + |
| 109 | +ASP.NET Core provides a [configuration](xref:fundamentals/configuration/index) 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. |
| 110 | + |
| 111 | +By [default](xref:fundamentals/configuration/index#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`. |
| 112 | + |
| 113 | +For managing confidential configuration data such as passwords, .NET Core provides the [Secret Manager](xref:security/app-secrets#secret-manager). For production secrets, we recommend [Azure Key Vault](xref:security/key-vault-configuration). |
| 114 | + |
| 115 | +For more information, see <xref:fundamentals/configuration/index>. |
| 116 | + |
| 117 | +## Environments |
| 118 | + |
| 119 | +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). |
| 120 | + |
| 121 | +The following example configures the exception handler and [HTTP Strict Transport Security Protocol (HSTS)](xref:security/enforcing-ssl#http-strict-transport-security-protocol-hsts) middleware when ***not*** running in the `Development` environment: |
| 122 | + |
| 123 | +[!code-csharp[](~/fundamentals/startup/6.0_samples/WebAll/Program.cs?name=snippet&highlight=10-14)] |
| 124 | + |
| 125 | +For more information, see <xref:fundamentals/environments>. |
| 126 | + |
| 127 | +## Logging |
| 128 | + |
| 129 | +ASP.NET Core supports a logging API that works with a variety of built-in and third-party logging providers. Available providers include: |
| 130 | + |
| 131 | +* Console |
| 132 | +* Debug |
| 133 | +* Event Tracing on Windows |
| 134 | +* Windows Event Log |
| 135 | +* TraceSource |
| 136 | +* Azure App Service |
| 137 | +* Azure Application Insights |
| 138 | + |
| 139 | +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: |
| 140 | + |
| 141 | +[!code-csharp[](~/fundamentals/index/samples/6.0/RazorPagesMovie/Pages/Movies/Index.cshtml.cs?name=snippet&highlight=3-10, 16-17)] |
| 142 | + |
| 143 | +For more information, see <xref:fundamentals/logging/index>. |
| 144 | + |
| 145 | +## Routing |
| 146 | + |
| 147 | +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. |
| 148 | + |
| 149 | +The following code, generated by the ASP.NET Core web application template, calls <xref:Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseRouting%2A>: |
| 150 | + |
| 151 | +[!code-csharp[](~/fundamentals/startup/6.0_samples/WebAll/Program.cs?name=snippet4&highlight=17)] |
| 152 | + |
| 153 | +For more information, see <xref:fundamentals/routing>. |
| 154 | + |
| 155 | +## Error handling |
| 156 | + |
| 157 | +ASP.NET Core has built-in features for handling errors, such as: |
| 158 | + |
| 159 | +* A developer exception page |
| 160 | +* Custom error pages |
| 161 | +* Static status code pages |
| 162 | +* Startup exception handling |
| 163 | + |
| 164 | +For more information, see <xref:fundamentals/error-handling>. |
| 165 | + |
| 166 | +## Make HTTP requests |
| 167 | + |
| 168 | +An implementation of `IHttpClientFactory` is available for creating `HttpClient` instances. The factory: |
| 169 | + |
| 170 | +* Provides a central location for naming and configuring logical `HttpClient` instances. For example, register and configure a *github* client for accessing GitHub. Register and configure a default client for other purposes. |
| 171 | +* Supports registration and chaining of multiple delegating handlers to build an outgoing request middleware pipeline. This pattern is similar to ASP.NET Core's inbound middleware pipeline. The pattern provides a mechanism to manage cross-cutting concerns for HTTP requests, including caching, error handling, serialization, and logging. |
| 172 | +* Integrates with *Polly*, a popular third-party library for transient fault handling. |
| 173 | +* Manages the pooling and lifetime of underlying `HttpClientHandler` instances to avoid common DNS problems that occur when managing `HttpClient` lifetimes manually. |
| 174 | +* Adds a configurable logging experience via <xref:Microsoft.Extensions.Logging.ILogger> for all requests sent through clients created by the factory. |
| 175 | + |
| 176 | +For more information, see <xref:fundamentals/http-requests>. |
| 177 | + |
| 178 | +## Content root |
| 179 | + |
| 180 | +The content root is the base path for: |
| 181 | + |
| 182 | +* The executable hosting the app (*.exe*). |
| 183 | +* Compiled assemblies that make up the app (*.dll*). |
| 184 | +* Content files used by the app, such as: |
| 185 | + * Razor files (`.cshtml`, `.razor`) |
| 186 | + * Configuration files (`.json`, `.xml`) |
| 187 | + * Data files (`.db`) |
| 188 | +* The [Web root](#web-root), typically the *wwwroot* folder. |
| 189 | + |
| 190 | +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](#web-root). Specify a different content root by setting its path when [building the host](#host). For more information, see [Content root](xref:fundamentals/host/generic-host#contentroot). |
| 191 | + |
| 192 | +## Web root |
| 193 | + |
| 194 | +The web root is the base path for public, static resource files, such as: |
| 195 | + |
| 196 | +* Stylesheets (`.css`) |
| 197 | +* JavaScript (`.js`) |
| 198 | +* Images (`.png`, `.jpg`) |
| 199 | + |
| 200 | +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](#host). For more information, see [Web root](xref:fundamentals/host/generic-host#webroot). |
| 201 | + |
| 202 | +Prevent publishing files in *wwwroot* with the [\<Content> project item](/visualstudio/msbuild/common-msbuild-project-items#content) in the project file. The following example prevents publishing content in *wwwroot/local* and its sub-directories: |
| 203 | + |
| 204 | +```xml |
| 205 | +<ItemGroup> |
| 206 | + <Content Update="wwwroot\local\**\*.*" CopyToPublishDirectory="Never" /> |
| 207 | +</ItemGroup> |
| 208 | +``` |
| 209 | + |
| 210 | +In Razor `.cshtml` files, `~/` points to the web root. A path beginning with `~/` is referred to as a *virtual path*. |
| 211 | + |
| 212 | +For more information, see <xref:fundamentals/static-files>. |
| 213 | + |
| 214 | +## Additional resources |
| 215 | + |
| 216 | +* [WebApplicationBuilder source code](https://github.com/dotnet/aspnetcore/blob/v6.0.1/src/DefaultBuilder/src/WebApplicationBuilder.cs) |
| 217 | + |
| 218 | +:::moniker-end |
0 commit comments