Back to Aspnetcore

Middleware7

aspnetcore/fundamentals/minimal-apis/includes/middleware7.md

latest4.3 KB
Original Source

:::moniker range="= aspnetcore-7.0"

WebApplication automatically adds the following middleware in Minimal API applications depending on certain conditions:

The following code is effectively what the automatic middleware being added to the app produces:

csharp
if (isDevelopment)
{
    app.UseDeveloperExceptionPage();
}

app.UseRouting();

if (isAuthenticationConfigured)
{
    app.UseAuthentication();
}

if (isAuthorizationConfigured)
{
    app.UseAuthorization();
}

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

app.UseEndpoints(e => {});

In some cases, the default middleware configuration isn't correct for the app and requires modification. For example, xref:Microsoft.AspNetCore.Builder.CorsMiddlewareExtensions.UseCors%2A should be called before xref:Microsoft.AspNetCore.Builder.AuthAppBuilderExtensions.UseAuthentication%2A and xref:Microsoft.AspNetCore.Builder.AuthorizationAppBuilderExtensions.UseAuthorization%2A. The app needs to call UseAuthentication and UseAuthorization if UseCors is called:

csharp
app.UseCors();
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:

csharp
app.Use((context, next) =>
{
    return next(context);
});

app.UseRouting();

// 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.
csharp
app.UseRouting();

app.MapGet("/", () => "hello world");

app.UseEndpoints(e => {});

app.Run(context =>
{
    context.Response.StatusCode = 404;
    return Task.CompletedTask;
});

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

:::moniker-end