ASP.NET Core Dependency Injection :👈 👉:ASP.NET Core Global Exception Handling and ProblemDetails

ASP.NET Core Middleware Explained: Custom Middleware and Request Pipeline Internals

ASP.NET Core Middleware Explained: Custom Middleware and Request Pipeline Internals

1. Introduction

ASP.NET Core Middleware is a component that participates in processing HTTP requests and responses. Middleware components are arranged into a pipeline, and each component can perform operations before and after the next component executes.

Examples of middleware include:

  • Exception handling
  • HTTPS redirection
  • Authentication
  • Authorization
  • Static file handling
  • Routing
  • CORS
  • Logging
  • Response compression

Understanding middleware is essential because almost every ASP.NET Core application uses it to process incoming HTTP requests.

2. Table of Contents

  1. What Is Middleware?
  2. How the Request Pipeline Works
  3. Request and Response Flow
  4. Understanding Use, Run and Map
  5. Middleware Execution Order
  6. Creating Custom Middleware
  7. Middleware with Dependency Injection
  8. Conventional Middleware vs IMiddleware
  9. Exception Handling Middleware
  10. Short-Circuiting the Pipeline
  11. Branching the Pipeline
  12. Built-in ASP.NET Core Middleware
  13. Request Pipeline Internals
  14. Middleware Performance and Best Practices
  15. Common Middleware Mistakes
  16. Interview Questions and Answers
  17. Summary

3. What Is Middleware?

Middleware is software that is assembled into an HTTP request-processing pipeline.

Each middleware component can:

  • Examine the incoming HTTP request.
  • Perform an operation before calling the next middleware.
  • Pass control to the next middleware.
  • Examine or modify the HTTP response after the next middleware completes.
  • Stop further processing and generate a response directly.

Simple Example

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
    Console.WriteLine("Before next middleware");
    await next();
    Console.WriteLine("After next middleware");
});
app.Run(async context =>
{
    await context.Response.WriteAsync("Hello from ASP.NET Core");
});
app.Run();

Here:

  • context: Represents the current HTTP request and response.
  • next: Represents the next middleware component.
  • await next(): Transfers control to the next component.
  • Code after await next(): Executes when the downstream pipeline completes.

4. How the Request Pipeline Works

ASP.NET Core processes requests through middleware components in the order they are registered.

For example:

app.UseMiddleware<LoggingMiddleware>();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseMiddleware<AuthorizationMiddleware>();
app.MapControllers();

The request travels through the pipeline from the first middleware to the last.

Pipeline Diagram

Incoming HTTP Request Logging Middleware Authentication Authorization Controller HTTP Response

The response travels back through the middleware components in reverse order, allowing each component to perform post-processing.

This reverse flow occurs when middleware awaits the next component and then continues executing.

5. Request and Response Flow

Middleware can execute code both before and after the next middleware.

Consider this example:

app.Use(async (context, next) =>
{
    Console.WriteLine("Middleware 1 - Before");
    await next();
    Console.WriteLine("Middleware 1 - After");
});
app.Use(async (context, next) =>
{
    Console.WriteLine("Middleware 2 - Before");
    await next();
    Console.WriteLine("Middleware 2 - After");
});
app.Run(async context =>
{
    Console.WriteLine("Endpoint Executed");
    await context.Response.WriteAsync("Hello World");
});

Execution Order

Middleware 1 - Before
    Middleware 2 - Before
        Endpoint Executed
    Middleware 2 - After
Middleware 1 - After

This is commonly called the middleware onion model.

Each middleware wraps the downstream components.

Important Point

The code before await next() executes during the request's forward journey.

The code after await next() executes during the response's return journey.

If middleware does not call next(), downstream middleware and endpoints are not executed.

6. Understanding Use, Run and Map

ASP.NET Core provides different methods for configuring middleware.

6.1 Use()

Use() adds middleware that can call the next middleware component.

app.Use(async (context, next) =>
{
    Console.WriteLine("Before");
    await next();
    Console.WriteLine("After");
});

Characteristics:

  • Can execute logic before and after the next middleware.
  • Can modify requests and responses.
  • Can continue or short-circuit the pipeline.

6.2 Run()

Run() adds terminal middleware. It does not accept a next delegate.

app.Run(async context =>
{
    await context.Response.WriteAsync("Request Completed");
});

Characteristics:

  • Does not pass control to another middleware.
  • Terminates the current pipeline branch.
  • Commonly used for simple terminal request handling.

6.3 Map()

Map() creates a separate pipeline branch based on a matching request path.

app.Map("/admin", adminApp =>
{
    adminApp.Run(async context =>
    {
        await context.Response.WriteAsync("Admin Area");
    });
});
app.Run(async context =>
{
    await context.Response.WriteAsync("Main Application");
});

Requests beginning with /admin are handled by the mapped branch. Other requests continue through the main pipeline.

Comparison

Method Purpose Calls Next?
Use() Adds middleware that can continue processing Yes
Run() Adds terminal middleware No
Map() Creates a path-based pipeline branch Branch-specific

Note: Map() branches the pipeline. It is different from endpoint mapping methods such as MapGet(), MapPost() and MapControllers().

7. Middleware Execution Order

Middleware registration order is extremely important.

ASP.NET Core does not automatically rearrange middleware into the correct order. Developers must register components in an appropriate sequence.

Typical Middleware Order

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
// 1. Handle exceptions early
app.UseExceptionHandler("/error");
// 2. Redirect HTTP requests to HTTPS
app.UseHttpsRedirection();
// 3. Serve static files
app.UseStaticFiles();
// 4. Enable routing
app.UseRouting();
// 5. Apply CORS policies
app.UseCors("MyPolicy");
// 6. Authenticate the user
app.UseAuthentication();
// 7. Authorize the user
app.UseAuthorization();
// 8. Map controllers
app.MapControllers();
app.Run();

The exact order depends on the application and its endpoint configuration, but some ordering requirements are important.

Important Ordering Rules

Exception handling should be early.

It should be placed early enough to catch exceptions thrown by downstream middleware.

Authentication must come before authorization.

app.UseAuthentication();
app.UseAuthorization();

Authentication identifies the user. Authorization determines whether that user has permission to access a resource.

CORS must be configured in the appropriate position.

When using endpoint routing, CORS middleware should normally run after routing and before authorization.

Static files are commonly served before authentication.

Static File Middleware can serve files without executing the later authentication and authorization middleware. This is suitable for public files. Protected files require an authorization-aware approach.

8. Creating Custom Middleware

Custom middleware allows developers to implement application-specific request-processing logic.

Examples include:

  • Request logging
  • Request timing
  • Custom headers
  • Correlation IDs
  • Request validation
  • Custom exception handling

There are different ways to create custom middleware.

8.1 Using app.Use()

For simple scenarios, middleware can be written directly inside Program.cs.

app.Use(async (context, next) =>
{
    Console.WriteLine("Request received");
    await next();
    Console.WriteLine("Response completed");
});

This is useful for small middleware components.

However, for reusable or complex middleware, a separate class is preferable.

8.2 Creating a Separate Middleware Class

Create a class named RequestLoggingMiddleware.cs.

using Microsoft.AspNetCore.Http;
public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    public RequestLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        Console.WriteLine(
            $"Request: {context.Request.Method} {context.Request.Path}");
        await _next(context);
        Console.WriteLine(
            $"Response Status: {context.Response.StatusCode}");
    }
}

Register it in Program.cs.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware<RequestLoggingMiddleware>();
app.MapGet("/", () => "Hello World");
app.Run();

Explanation

  • RequestDelegate: Represents the next component in the HTTP request pipeline.
  • HttpContext: Provides access to the current HTTP request and response.
  • InvokeAsync(): The middleware execution method. ASP.NET Core invokes it when a request reaches this middleware.
  • _next(context): Passes the current request to the next middleware component.

8.3 Creating a Reusable Middleware Extension Method

To make custom middleware easier to register, create an extension method.

using Microsoft.AspNetCore.Builder;
public static class RequestLoggingMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestLogging(
        this IApplicationBuilder app)
    {
        return app.UseMiddleware<RequestLoggingMiddleware>();
    }
}

Register it using:

app.UseRequestLogging();

This provides a clean and readable registration syntax.

9. Middleware with Dependency Injection

ASP.NET Core supports dependency injection in middleware.

For conventional middleware, constructor-injected dependencies are generally created when the middleware instance is constructed during application pipeline setup.

This means constructor injection should normally be used for singleton-compatible dependencies.

For scoped or transient dependencies that need to be resolved per request, use InvokeAsync() method injection.

Example: Injecting ILogger

public class LoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<LoggingMiddleware> _logger;
    public LoggingMiddleware(
        RequestDelegate next,
        ILogger<LoggingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        _logger.LogInformation(
            "Request started: {Path}",
            context.Request.Path);
        await _next(context);
        _logger.LogInformation(
            "Request completed with status {StatusCode}",
            context.Response.StatusCode);
    }
}

Injecting a Scoped Service

Suppose IUserService is registered as scoped:

builder.Services.AddScoped<IUserService, UserService>();

Do not inject it into the constructor of conventional middleware because the middleware instance can live for the lifetime of the application.

Instead, inject it into InvokeAsync().

public class UserMiddleware
{
    private readonly RequestDelegate _next;
    public UserMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(
        HttpContext context,
        IUserService userService)
    {
        var user = await userService.GetCurrentUserAsync();
        await _next(context);
    }
}

ASP.NET Core resolves the method-injected service from the current request's service scope.

10. Conventional Middleware vs IMiddleware

ASP.NET Core supports two common middleware implementation patterns.

10.1 Conventional Middleware

A conventional middleware class:

  • Accepts RequestDelegate in its constructor.
  • Exposes an Invoke or InvokeAsync method.
  • Can use constructor injection for dependencies suitable for the middleware instance's lifetime.
  • Can receive scoped dependencies through method injection.

Example:

public class CustomMiddleware
{
    private readonly RequestDelegate _next;
    public CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        await _next(context);
    }
}

Registration:

app.UseMiddleware<CustomMiddleware>();

10.2 IMiddleware

IMiddleware allows middleware to be created through the dependency injection container.

public class CustomMiddleware : IMiddleware
{
    private readonly IUserService _userService;
    public CustomMiddleware(IUserService userService)
    {
        _userService = userService;
    }
    public async Task InvokeAsync(
        HttpContext context,
        RequestDelegate next)
    {
        var user = await _userService.GetCurrentUserAsync();
        await next(context);
    }
}

Register the middleware and its dependencies:

builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddTransient<CustomMiddleware>();

Use it in the pipeline:

app.UseMiddleware<CustomMiddleware>();

The middleware is resolved through the request's service provider. Its lifetime can therefore be controlled through DI registration.

Comparison

Feature Conventional Middleware IMiddleware
Constructor Receives RequestDelegate Receives normal DI dependencies
Execution method Invoke or InvokeAsync InvokeAsync
Creation Middleware pipeline activation DI container
Scoped constructor dependencies Not suitable for normal constructor injection Supported with an appropriate scoped/transient registration
Registration Usually no service registration required Must be registered in DI
Best suited for General reusable middleware Middleware requiring DI-managed lifetimes

11. Exception Handling Middleware

Exception handling middleware catches unhandled exceptions from downstream components and converts them into appropriate HTTP responses.

Without exception handling, an unhandled exception can result in an unsuccessful request and an error response.

Using Built-in Exception Handling

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseExceptionHandler("/error");
app.MapGet("/error", () =>
{
    return Results.Problem(
        title: "An unexpected error occurred.",
        statusCode: 500);
});
app.MapGet("/test", () =>
{
    throw new Exception("Something went wrong");
});
app.Run();

The exception handler processes the exception and re-executes the request using the configured error path.

In production applications, do not expose internal exception details, stack traces, database information or secrets to clients.

Custom Exception Middleware

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<ExceptionMiddleware> _logger;
    public ExceptionMiddleware(
        RequestDelegate next,
        ILogger<ExceptionMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Unhandled exception occurred");
            if (context.Response.HasStarted)
            {
                throw;
            }
            context.Response.Clear();
            context.Response.StatusCode = 500;
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsJsonAsync(new
            {
                message = "An unexpected error occurred."
            });
        }
    }
}

Registration:

app.UseMiddleware<ExceptionMiddleware>();

The exception middleware should be registered early so it can catch exceptions from downstream components.

12. Short-Circuiting the Pipeline

Short-circuiting means stopping the request pipeline before it reaches the remaining middleware components.

A middleware can short-circuit by not calling next().

Example

app.Use(async (context, next) =>
{
    if (context.Request.Path == "/blocked")
    {
        context.Response.StatusCode = 403;
        await context.Response.WriteAsync("Access Denied");
        return;
    }
    await next();
});

For /blocked:

  • The middleware detects the path.
  • It generates a response.
  • It does not call next().
  • Remaining middleware and endpoints are skipped.

When Is Short-Circuiting Useful?

  • Blocking unwanted requests.
  • Rejecting invalid requests.
  • Returning cached responses.
  • Handling health-check endpoints.
  • Serving static files.

Short-circuiting should be used carefully because it can bypass later middleware such as authentication, authorization, logging or other processing.

13. Branching the Pipeline

Sometimes different request paths require different processing logic.

ASP.NET Core supports pipeline branching through Map().

Example

app.Map("/api", apiApp =>
{
    apiApp.Use(async (context, next) =>
    {
        Console.WriteLine("API branch middleware");
        await next();
    });
    apiApp.Run(async context =>
    {
        await context.Response.WriteAsync("API Pipeline");
    });
});
app.Map("/admin", adminApp =>
{
    adminApp.Run(async context =>
    {
        await context.Response.WriteAsync("Admin Pipeline");
    });
});
app.Run(async context =>
{
    await context.Response.WriteAsync("Main Pipeline");
});

Request Behavior

Request Path Executed Pipeline
/api API branch
/api/users API branch
/admin Admin branch
/admin/dashboard Admin branch
/home Main pipeline

Map() matches a path prefix and removes the matched path from Request.Path within the branch. The original path is available through Request.PathBase.

MapWhen()

MapWhen() branches based on a custom condition rather than only a path prefix.

app.MapWhen(
    context => context.Request.Query.ContainsKey("mobile"),
    mobileApp =>
    {
        mobileApp.Run(async context =>
        {
            await context.Response.WriteAsync("Mobile Request");
        });
    });

This branch executes when the query string contains the mobile key.

14. Built-in ASP.NET Core Middleware

ASP.NET Core provides many built-in middleware components.

Middleware Purpose
UseExceptionHandler Handles unhandled exceptions
UseDeveloperExceptionPage Displays detailed development errors
UseHttpsRedirection Redirects HTTP requests to HTTPS
UseHsts Adds HTTP Strict Transport Security headers
UseStaticFiles Serves static files
UseRouting Matches requests to endpoints
UseCors Applies Cross-Origin Resource Sharing policies
UseAuthentication Identifies the current user
UseAuthorization Enforces authorization policies
UseResponseCaching Enables HTTP response caching
UseResponseCompression Compresses HTTP responses
UseSession Enables session state
UseRateLimiter Applies rate-limiting policies

Not every application needs every middleware component. Add only the middleware required by the application's functionality and security requirements.

15. Request Pipeline Internals

Understanding how ASP.NET Core constructs the pipeline helps explain middleware execution.

15.1 RequestDelegate

The central abstraction behind middleware is RequestDelegate.

public delegate Task RequestDelegate(HttpContext context);

It represents a function that receives an HttpContext and returns a Task.

Each middleware component ultimately participates in a chain of request delegates.

15.2 How Middleware Is Connected

Conceptually, the pipeline looks like this:

RequestDelegate 1
      |
      v
RequestDelegate 2
      |
      v
RequestDelegate 3
      |
      v
Endpoint

Each middleware receives a reference to the next delegate and decides when to invoke it.

A simplified conceptual implementation looks like this:

public class SimpleMiddleware
{
    private readonly RequestDelegate _next;
    public SimpleMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        // Before downstream execution
        await _next(context);
        // After downstream execution
    }
}

This is the fundamental middleware pattern.

15.3 Pipeline Construction

When the application starts, ASP.NET Core builds the middleware pipeline from the registered components.

For conventional middleware, the framework creates middleware instances and connects their request delegates.

The final delegate represents the complete pipeline.

When an HTTP request arrives, the server invokes this pipeline with the request's HttpContext.

15.4 What Is HttpContext?

HttpContext represents the current HTTP request and response.

Important properties include:

Property Purpose
Request Incoming HTTP request
Response Outgoing HTTP response
User Current authenticated principal
RequestServices Request-scoped service provider
TraceIdentifier Identifier for the current request
Items Request-specific key-value storage
Connection Connection information

Example:

app.Use(async (context, next) =>
{
    var method = context.Request.Method;
    var path = context.Request.Path;
    var user = context.User;
    context.Items["RequestStart"] = DateTime.UtcNow;
    await next();
});

HttpContext.Items is useful for sharing data between middleware components during a single request. It is not intended for long-term storage.

15.5 How Use() Builds the Pipeline

Conceptually, each Use() component wraps the remaining pipeline.

For example:

app.Use(Middleware1);
app.Use(Middleware2);
app.Use(Middleware3);

The resulting execution structure is similar to:

Middleware1(
    Middleware2(
        Middleware3(
            TerminalHandler
        )
    )
)

This explains why requests move forward through the middleware and responses unwind in reverse order.

The actual framework implementation includes additional details for middleware activation, endpoint routing, branching and other features. The diagram represents the basic composition model.

16. Middleware Performance and Best Practices

16.1 Keep Middleware Focused

Each middleware should perform a specific responsibility.

For example:

  • Logging middleware handles logging.
  • Authentication middleware identifies users.
  • Authorization middleware checks permissions.
  • Exception middleware handles errors.

Avoid placing unrelated business logic into middleware.

16.2 Avoid Blocking Calls

Avoid synchronous blocking operations such as:

var result = SomeAsyncMethod().Result;

Prefer asynchronous execution:

var result = await SomeAsyncMethod();

This helps avoid unnecessary thread blocking.

16.3 Avoid Large Request and Response Buffering

Do not read or buffer entire request and response bodies unless required.

Large payloads can increase memory usage and reduce application throughput.

16.4 Use ILogger Instead of Console.WriteLine

Prefer structured logging:

_logger.LogInformation(
    "Request {Method} {Path}",
    context.Request.Method,
    context.Request.Path);

This provides better integration with logging providers and monitoring systems.

16.5 Do Not Store Request-Specific Data in Middleware Fields

Conventional middleware instances can be shared across requests.

Avoid storing request-specific information in instance fields.

Incorrect:

public class BadMiddleware
{
    private readonly RequestDelegate _next;
    private string? _currentUser;
    public BadMiddleware(RequestDelegate next)
    {
        _next = next;
    }
}

Concurrent requests could overwrite the shared field.

Prefer local variables or HttpContext.Items for request-specific data.

16.6 Register Middleware in the Correct Order

Incorrect middleware ordering can cause security and functionality problems.

For example, authorization should not run before authentication when authorization depends on the authenticated user.

16.7 Use Built-in Middleware When Available

Before creating custom middleware, check whether ASP.NET Core already provides the required functionality.

For example, use:

  • UseExceptionHandler() for exception handling.
  • UseHttpsRedirection() for HTTPS redirection.
  • UseCors() for CORS.
  • UseRateLimiter() for rate limiting.

Built-in middleware is generally preferable when it satisfies the requirement.

17. Common Middleware Mistakes

Mistake 1: Forgetting to Call next()

app.Use(async (context, next) =>
{
    Console.WriteLine("Request received");
});

Problem: The middleware does not call next(), so downstream processing is skipped.

Correct:

app.Use(async (context, next) =>
{
    Console.WriteLine("Request received");
    await next();
});

Mistake 2: Incorrect Middleware Order

app.UseAuthorization();
app.UseAuthentication();

Problem: Authorization runs before authentication.

Correct:

app.UseAuthentication();
app.UseAuthorization();

Mistake 3: Injecting Scoped Services into Conventional Middleware Constructors

Problem: Conventional middleware instances are generally created during pipeline construction, so constructor injection of scoped services can create lifetime problems.

Correct: Use InvokeAsync() method injection or implement IMiddleware with an appropriate DI lifetime.

Mistake 4: Modifying the Response After It Has Started

Once the response has started, headers and status code can no longer be changed.

Check:

if (!context.Response.HasStarted)
{
    context.Response.StatusCode = 500;
}

Mistake 5: Performing Expensive Operations in Every Middleware

Problem: Every request may pass through the middleware, increasing latency.

Solution: Keep middleware lightweight and perform only necessary work.

Mistake 6: Exposing Exception Details to Clients

Problem: Stack traces and internal exception information can expose sensitive implementation details.

Solution: Log detailed exceptions internally and return safe error responses to clients.

18. Interview Questions and Answers

1. What is middleware in ASP.NET Core?

Middleware is a component that participates in processing HTTP requests and responses. Multiple middleware components are arranged into a pipeline.

2. What is the ASP.NET Core request pipeline?

It is an ordered sequence of middleware components through which an HTTP request passes before reaching its endpoint.

3. What is the difference between Use() and Run()?

Use() can call the next middleware and continue processing. Run() adds terminal middleware and does not accept a next delegate.

4. What is the purpose of Map()?

Map() creates a separate middleware pipeline for requests matching a specified path prefix.

5. What is short-circuiting?

Short-circuiting occurs when middleware generates a response without calling the next middleware component.

6. Why is middleware order important?

Middleware executes in registration order. Incorrect ordering can affect authentication, authorization, exception handling, CORS and other application behavior.

7. What is RequestDelegate?

RequestDelegate is a delegate that accepts an HttpContext and returns a Task. It represents a component in the HTTP request pipeline.

8. What is HttpContext?

HttpContext provides access to the current HTTP request, response, user, connection and request-specific services.

9. How do you create custom middleware?

Create a class that accepts RequestDelegate in its constructor and implements an Invoke or InvokeAsync method. Register it using app.UseMiddleware<T>().

10. What is the difference between conventional middleware and IMiddleware?

Conventional middleware is activated through the middleware pipeline and normally uses constructor injection for dependencies suitable for its lifetime. IMiddleware is activated through DI, allowing its lifetime to be managed by the container.

11. Can middleware access scoped services?

Yes. Conventional middleware can receive scoped dependencies through its InvokeAsync() method parameters. Alternatively, use IMiddleware registered with an appropriate lifetime.

12. What happens if middleware does not call next()?

The remaining middleware components and endpoint are not executed for that request.

13. Why should exception middleware be registered early?

It needs to wrap downstream middleware so that it can catch exceptions thrown by those components.

14. What is the difference between Map() and MapWhen()?

Map() branches based on a path prefix. MapWhen() branches based on a custom condition involving the request context.

15. Can middleware modify the HTTP response?

Yes. Middleware can modify response headers, status codes and body content, provided the response has not already started where applicable.

16. What is the onion model in middleware?

It describes how middleware executes before the next component and then resumes after the downstream component completes. The response therefore unwinds in reverse order.

17. What is the purpose of HttpContext.Items?

It stores temporary key-value data that can be shared between middleware and other components during a single HTTP request.

18. What is the difference between middleware and filters?

Middleware operates at the HTTP request pipeline level and can run before endpoint execution. MVC filters operate within the MVC action execution pipeline and provide access to MVC-specific contexts and stages.

19. Summary

Concept Key Point
Middleware Component that processes HTTP requests and responses
Request Pipeline Ordered chain of middleware
Use() Adds middleware that can call the next component
Run() Adds terminal middleware
Map() Creates a path-based branch
MapWhen() Creates a condition-based branch
RequestDelegate Represents the next request-processing delegate
HttpContext Provides request and response information
Custom Middleware Application-specific request-processing component
IMiddleware DI-activated middleware implementation
Short-Circuiting Stops further pipeline execution
Execution Order Determines how requests and responses are processed

20. Conclusion

Middleware is one of the most important concepts in ASP.NET Core. It provides a flexible way to process HTTP requests and responses through a sequence of independent components.

Understanding Use(), Run(), Map(), custom middleware, dependency injection and middleware execution order helps developers build applications that are maintainable, secure and efficient.

Understanding Use(), Run(), Map(), custom middleware, dependency injection and middleware execution order helps developers build applications that are maintainable, secure and efficient.

🔙
ASP.NET Core Dependency Injection :👈 👉:ASP.NET Core Global Exception Handling and ProblemDetails