Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 20 additions & 12 deletions aspnetcore/fundamentals/minimal-apis/includes/middleware8.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
:::moniker range=">= aspnetcore-8.0"

[`WebApplication`](xref:fundamentals/minimal-apis/webapplication) automatically adds the following middleware in [Minimal API applications](xref:fundamentals/apis) depending on certain conditions:
* [`UseDeveloperExceptionPage`](/dotnet/api/microsoft.aspnetcore.diagnostics.developerexceptionpagemiddleware) is added first when the [`HostingEnvironment`](xref:fundamentals/environments) is `"Development"`.
* [`UseRouting`](/dotnet/api/microsoft.aspnetcore.builder.endpointroutingapplicationbuilderextensions.userouting) is added second if user code didn't already call `UseRouting` and if there are endpoints configured, for example `app.MapGet`.
* [`UseEndpoints`](/dotnet/api/microsoft.aspnetcore.builder.endpointroutingapplicationbuilderextensions.useendpoints) is added at the end of the middleware pipeline if any endpoints are configured.
* [`UseAuthentication`](/dotnet/api/microsoft.aspnetcore.builder.authappbuilderextensions.useauthentication) is added immediately after `UseRouting` if user code didn't already call `UseAuthentication` and if [`IAuthenticationSchemeProvider`](/dotnet/api/microsoft.aspnetcore.authentication.iauthenticationschemeprovider) can be detected in the service provider. `IAuthenticationSchemeProvider` is added by default when using [`AddAuthentication`](/dotnet/api/microsoft.extensions.dependencyinjection.authenticationservicecollectionextensions.addauthentication), and services are detected using [`IServiceProviderIsService`](/dotnet/api/microsoft.extensions.dependencyinjection.iserviceproviderisservice).
* [`UseAuthorization`](/dotnet/api/microsoft.aspnetcore.builder.authorizationappbuilderextensions.useauthorization) is added next if user code didn't already call `UseAuthorization` and if [`IAuthorizationHandlerProvider`](/dotnet/api/microsoft.aspnetcore.authorization.iauthorizationhandlerprovider) can be detected in the service provider. `IAuthorizationHandlerProvider` is added by default when using [`AddAuthorization`](/dotnet/api/microsoft.extensions.dependencyinjection.authenticationservicecollectionextensions.addauthentication), and services are detected using `IServiceProviderIsService`.
[WebApplication](xref:fundamentals/minimal-apis/webapplication) automatically adds the following middleware in [Minimal API applications](xref:fundamentals/apis) depending on certain conditions:

* [UseDeveloperExceptionPage](/dotnet/api/microsoft.aspnetcore.diagnostics.developerexceptionpagemiddleware) is added first when the [HostingEnvironment](xref:fundamentals/environments) is `"Development"`.

* [UseRouting](/dotnet/api/microsoft.aspnetcore.builder.endpointroutingapplicationbuilderextensions.userouting) is added second, if the user code didn't already call `UseRouting` and endpoints are configured, for example `app.MapGet`.

* [UseEndpoints](/dotnet/api/microsoft.aspnetcore.builder.endpointroutingapplicationbuilderextensions.useendpoints) is added at the end of the middleware pipeline if endpoints are configured.

* [UseAuthentication](/dotnet/api/microsoft.aspnetcore.builder.authappbuilderextensions.useauthentication) is added immediately after `UseRouting`, if user code didn't already call `UseAuthentication` and if [IAuthenticationSchemeProvider](/dotnet/api/microsoft.aspnetcore.authentication.iauthenticationschemeprovider) can be detected in the service provider. `IAuthenticationSchemeProvider` is added by default when you use [AddAuthentication](/dotnet/api/microsoft.extensions.dependencyinjection.authenticationservicecollectionextensions.addauthentication), and services are detected by using [IServiceProviderIsService](/dotnet/api/microsoft.extensions.dependencyinjection.iserviceproviderisservice).

* [UseAuthorization](/dotnet/api/microsoft.aspnetcore.builder.authorizationappbuilderextensions.useauthorization) is added next, if user code didn't already call `UseAuthorization` and if [IAuthorizationHandlerProvider](/dotnet/api/microsoft.aspnetcore.authorization.iauthorizationhandlerprovider) can be detected in the service provider. `IAuthorizationHandlerProvider` is added by default when you use [AddAuthorization](/dotnet/api/microsoft.extensions.dependencyinjection.authenticationservicecollectionextensions.addauthentication), and services are detected by using `IServiceProviderIsService`.

* User configured middleware and endpoints are added between `UseRouting` and `UseEndpoints`.

The following code is effectively what the automatic middleware being added to the app produces:
Expand All @@ -28,10 +34,10 @@ if (isAuthorizationConfigured)
app.UseAuthorization();
}

// user middleware/endpoints
// User middleware/endpoints
app.CustomMiddleware(...);
app.MapGet("/", () => "hello world");
// end user middleware/endpoints
// End user middleware/endpoints

app.UseEndpoints(e => {});
```
Expand All @@ -44,7 +50,7 @@ app.UseAuthentication();
app.UseAuthorization();
```

If middleware should be run before route matching occurs, <xref:Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseRouting%2A> should be called and the middleware should be placed before the call to `UseRouting`. <xref:Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseEndpoints%2A> isn't required in this case as it is automatically added as described previously:
If middleware should run before route matching occurs, <xref:Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseRouting%2A> should be called and the middleware should be placed before the call to `UseRouting`. <xref:Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseEndpoints%2A> isn't required in this case because it's automatically added as described earlier:

```csharp
app.Use((context, next) =>
Expand All @@ -54,13 +60,15 @@ app.Use((context, next) =>

app.UseRouting();

// other middleware and endpoints
// Other middleware and endpoints
```

When adding a terminal middleware:

* The middleware must be added after `UseEndpoints`.
* The app needs to call `UseRouting` and `UseEndpoints` so that the terminal middleware can be placed at the correct location.

* The app needs to call `UseRouting` and `UseEndpoints` so the terminal middleware can be placed at the correct location.

```csharp
app.UseRouting();

Expand All @@ -77,6 +85,6 @@ app.Run(context =>

Terminal middleware is middleware that runs if no endpoint handles the request.

For information on antiforgery middleware in Minimal APIs, see <xref:security/anti-request-forgery#afwma>
For information on antiforgery middleware in Minimal APIs, see <xref:security/anti-request-forgery#afwma>.

:::moniker-end
49 changes: 27 additions & 22 deletions aspnetcore/fundamentals/minimal-apis/includes/route-handlers.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
Route handlers are methods that execute when the route matches. Route handlers can be a lambda expression, a local function, an instance method or a static method. Route handlers can be synchronous or asynchronous.
Route handlers are methods that execute when the route matches. Route handlers can be a lambda expression, a local function, an instance method, or a static method. Route handlers can be synchronous or asynchronous.

The following sections provide examples of different route handlers.

### Lambda expression

Expand All @@ -16,58 +18,61 @@ Route handlers are methods that execute when the route matches. Route handlers c

[!code-csharp[](~/fundamentals/minimal-apis/7.0-samples/WebMinAPIs/Program.cs?name=snippet_sm)]

### Endpoint defined outside of `Program.cs`
### Endpoint defined outside of Program.cs

Minimal APIs don't have to be located in `Program.cs`.
Minimal APIs don't have to be located in the _Program.cs_ file. For example, you can set up the structure in the _Program.cs_ file, and define the endpoint in a separate file:

`Program.cs`
**Program.cs**

[!code-csharp[](~/fundamentals/minimal-apis/8.0-samples/MinAPISeparateFile/Program.cs)]

`TodoEndpoints.cs`
**TodoEndpoints.cs**

[!code-csharp[](~/fundamentals/minimal-apis/8.0-samples/MinAPISeparateFile/TodoEndpoints.cs)]

See also [Route groups](#route-groups) later in this article.
For more information, see the [Route groups](#route-groups) section later in this article.

### Named endpoints and link generation

Endpoints can be given names in order to generate URLs to the endpoint. Using a named endpoint avoids having to hard code paths in an app:
You can supply a name for your endpoints to generate URLs that target the endpoint. Using a named endpoint avoids having to hard code paths in an app:

[!code-csharp[](~/fundamentals/minimal-apis/samples/WebMinAPIs/Program.cs?name=snippet_nr)]

The preceding code displays `The link to the hello route is /hello` from the `/` endpoint.
The preceding code displays the message _`The link to the hello route is /hello`_ from the `/` (forward slash) endpoint.

**NOTE**: Endpoint names are case sensitive.
#### Criteria for endpoint names

Endpoint names:
Endpoint names must satisfy the following criteria:

* Must be globally unique.
* Are used as the OpenAPI operation id when OpenAPI support is enabled. For more information, see [OpenAPI](xref:fundamentals/openapi/aspnetcore-openapi).
- Endpoint names are case sensitive.
* Endpoint names must be globally unique.
* Endpoint names are used as the OpenAPI operation identifier (ID) when OpenAPI support is enabled. For more information, see [Generate OpenAPI documents](xref:fundamentals/openapi/aspnetcore-openapi).

### Route Parameters
### Route parameters

Route parameters can be captured as part of the route pattern definition:

[!code-csharp[](~/fundamentals/minimal-apis/7.0-samples/WebMinAPIs/Program.cs?name=snippet_rp)]

The preceding code returns `The user id is 3 and book id is 7` from the URI `/users/3/books/7`.
The preceding code returns the message _The user id is 3 and book id is 7_ from the URI `/users/3/books/7`.

The route handler can declare the parameters to capture. When a request is made to a route with parameters declared to capture, the parameters are parsed and passed to the handler. This makes it easy to capture the values in a type safe way. In the preceding code, `userId` and `bookId` are both `int`.
The route handler can declare the parameters to capture. When a request is made to a route with parameters declared to capture, the parameters are parsed and passed to the handler. This approach makes it easy to capture the values in a type-safe way. In the preceding code, the `userId` and `bookId` parameters are both type `int`.

In the preceding code, if either route value cannot be converted to an `int`, an exception is thrown. The GET request `/users/hello/books/3` throws the following exception:
In the preceding code, if either route value can't be converted to an `int`, the command throws an exception. The GET request `/users/hello/books/3` throws the following exception:

**`BadHttpRequestException: Failed to bind parameter "int userId" from "hello".`**
```output
BadHttpRequestException: Failed to bind parameter "int userId" from "hello".
```

### Wildcard and catch all routes

The following catch all route returns `Routing to hello` from the `/posts/hello' endpoint:
The following catch all route returns _Routing to hello_ from the `/posts/hello` endpoint:

[!code-csharp[](~/fundamentals/minimal-apis/7.0-samples/WebMinAPIs/Program.cs?name=snippet_wild)]

### Route constraints

Route constraints constrain the matching behavior of a route.
Route constraints restrict the matching behavior of a route.

```csharp
var builder = WebApplication.CreateBuilder(args);
Expand All @@ -82,13 +87,13 @@ app.Run();

The following table demonstrates the preceding route templates and their behavior:

| Route Template | Example Matching URI |
|--|--|
| Route template | Example matching URI |
|---|---|
| `/todos/{id:int}` | `/todos/1` |
| `/todos/{text}` | `/todos/something` |
| `/posts/{slug:regex(^[a-z0-9_-]+$)}` | `/posts/mypost` |

For more information, see [Route constraint reference](xref:fundamentals/routing) in <xref:fundamentals/routing>.
For more information, see [Route constraint reference](xref:fundamentals/routing#route-constraints) in <xref:fundamentals/routing>.

### Route groups

Expand Down
16 changes: 12 additions & 4 deletions aspnetcore/fundamentals/minimal-apis/middleware.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
---
title: Middleware with Minimal API applications
author: BrennanConroy
description: Use middleware in Minimal API applications
description: Use middleware in Minimal API applications, including automatic middleware, user-configured middleware, and terminal middleware.
ms.author: wpickett
ms.date: 02/16/2024
ms.date: 04/28/2026
monikerRange: '>= aspnetcore-7.0'
uid: fundamentals/minimal-apis/middleware

# customer intent: As an ASP.NET developer, I want to use middleware in ASP.NET Code, so I can use the functionality to handle requests and responses in my Minimal API apps.
---

# Middleware in Minimal API apps

[!INCLUDE[](~/includes/not-latest-version.md)]

This article describes how to use middleware in Minimal API applications. Take advantage of automatic middleware in your Minimal API apps, or define user-configured middleware and terminal middleware.

## Available middleware

[!INCLUDE [webapplication7](~/fundamentals/minimal-apis/includes/middleware7.md)]
[!INCLUDE [webapplication8](~/fundamentals/minimal-apis/includes/middleware8.md)]

For more information about middleware see [ASP.NET Core Middleware](xref:fundamentals/middleware/index), and the [list of built-in middleware](xref:fundamentals/middleware/index#built-in-middleware) that can be added to applications.
## Related content

For more information about Minimal APIs see [APIs overview](xref:fundamentals/apis).
- [ASP.NET Core Middleware](xref:fundamentals/middleware/index)
- [Built-in middleware (list)](xref:fundamentals/middleware/index#built-in-middleware)
- [Minimal APIs overview](xref:fundamentals/apis)
Loading
Loading