Middleware Pipeline
Use, Run, Map and writing custom middleware.
Middleware Pipeline in ASP.NET Core
Interview-ready definition: Middleware is software assembled into an HTTP request pipeline. Each middleware can inspect or modify the request, call the next component, perform work after the next component completes, or stop the pipeline by producing a response.
Middleware is one of the most important concepts in ASP.NET Core. Routing, authentication, authorization, exception handling, logging, static files, and endpoint execution all participate in the request pipeline.
Learning objectives
By the end of this module, you should be able to:
- Explain how HTTP requests move through middleware.
- Distinguish
Use,Run, andMap. - Understand short-circuiting and the downstream delegate.
- Write inline and class-based custom middleware.
- Use
RequestDelegate,HttpContext, and dependency injection correctly. - Place exception handling, routing, authentication, authorization, and endpoints in the right order.
- Avoid common lifetime, performance, security, and response-body mistakes.
- Answer common middleware interview questions with practical examples.
1. What is middleware?
Think of an HTTP request as a visitor moving through an office. Reception checks the visitor in, security verifies identity, a department decides whether the visitor may enter, and the requested team handles the work. An ASP.NET Core request behaves similarly: middleware components form a chain, and each component is responsible for a particular concern.
Typical middleware responsibilities include logging, exception handling, serving static files, matching routes, authenticating users, authorizing access, applying CORS policies, compressing responses, and executing an endpoint.
A simple pipeline
This is a conceptual example, not a universal order for every application.
The core idea
Middleware receives an HttpContext and may have access to a delegate that invokes the next component.
async Task Middleware(HttpContext context, RequestDelegate next)
{
// Work before the next component.
await next(context);
// Work after the next component.
}
The registration APIs adapt the middleware shape for you, so you normally register middleware with app.Use(...) or app.UseMiddleware<T>().
2. How the request pipeline works
Middleware is registered in Program.cs. Registration order determines the order in which middleware runs for an incoming request. For middleware that calls the next component, execution has two phases:
- Inbound phase: code before
await next(context). - Outbound phase: code after
await next(context).
Example: trace the request
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
Console.WriteLine("A: before");
await next(context);
Console.WriteLine("A: after");
});
app.Use(async (context, next) =>
{
Console.WriteLine("B: before");
await next(context);
Console.WriteLine("B: after");
});
app.Run(async context =>
{
Console.WriteLine("C: endpoint");
await context.Response.WriteAsync("Hello from the endpoint");
});
app.Run();
For a request reaching this pipeline, output is:
A: before
B: before
C: endpoint
B: after
A: after
The first middleware enters, calls the next one, and pauses. The second enters, calls the terminal delegate, and pauses. When the terminal delegate completes, execution unwinds in reverse order.
Important: await next(context) does not create a new HTTP request. It transfers execution to the next delegate in the same pipeline.
What if middleware does not call next?
It can short-circuit the pipeline:
app.Use(async (context, next) =>
{
if (!context.Request.Headers.ContainsKey("X-Client-Version"))
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync("Missing client version.");
return;
}
await next(context);
});
If the header is missing, downstream middleware and the endpoint do not execute. Use short-circuiting intentionally: accidentally omitting next can make an application path appear broken.
3. Use, Run, and Map
These APIs are frequently compared in interviews.
| API | Purpose | Calls next component? | Typical use |
|---|---|---|---|
Use | Adds middleware that can run before and after downstream execution | Usually yes, by calling next | Logging, timing, request checks |
Run | Adds a terminal delegate | No downstream next delegate is provided | Simple terminal response |
Map | Branches the pipeline based on a matching request path | The branch runs independently of the main pipeline unless it continues within the branch | Path-specific behavior |
3.1 Use: continue or short-circuit
Use is the general-purpose inline middleware registration method.
app.Use(async (context, next) =>
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
await next(context);
stopwatch.Stop();
Console.WriteLine(
$"Request completed in {stopwatch.Elapsed.TotalMilliseconds:F1} ms");
});
The next delegate is a RequestDelegate, conceptually represented as:
public delegate Task RequestDelegate(HttpContext context);
Use Use when you need logic before and/or after the rest of the pipeline, or when you may reject a request before it reaches downstream components. Stopwatch is preferable to wall-clock time for elapsed-time measurement.
3.2 Run: terminate the pipeline
Run registers a terminal request delegate. It doesn't receive a next delegate.
app.Run(async context =>
{
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("This is the terminal response.");
});
If this Run is reached, later middleware registered after it will not execute for that request.
Run is also the method used to start the web application:
app.Run();
These are different overloads with different purposes:
app.Run(async context => ...)adds a terminal request delegate.app.Run()starts the web host and begins accepting requests.
A common interview trap is confusing these calls.
3.3 Map: branch by path
Map creates a branch based on a path prefix.
app.Map("/admin", adminApp =>
{
adminApp.Run(async context =>
{
await context.Response.WriteAsync("Admin branch");
});
});
app.Run(async context =>
{
await context.Response.WriteAsync("Main pipeline");
});
A request to /admin or a matching path under that branch is handled by the branch. Other requests continue through the main pipeline. By default, Map matches a path segment, not merely an arbitrary string prefix: /admin/reports matches the /admin branch, while /administrator does not match it as the same path segment.
Within a Map branch, the matched prefix is removed from Request.Path and appended to Request.PathBase.
Map versus endpoint routing
Do not confuse app.Map("/admin", ...) with app.MapGet("/admin", ...).
app.Map("/admin", branch => ...)branches the middleware pipeline by path.app.MapGet("/admin", handler)registers an HTTP GET endpoint through endpoint routing.
app.MapGet("/health", () => Results.Ok(new { status = "healthy" }));
Use endpoint routing for ordinary API or page endpoints. Use middleware branching when you genuinely need a separate pipeline path.
Quick decision guide
- Need to inspect a request and then continue? Use
- Need to return a response and stop? Run, or short-circuit inside
Use - Need a separate pipeline for a path prefix? Map
- Need to define a GET/POST API endpoint? MapGet, MapPost, and related endpoint-routing methods
4. Writing custom middleware
Built-in middleware covers many common requirements, but applications sometimes need custom cross-cutting behavior, such as adding a correlation ID, measuring request duration, enforcing a custom request header, adding a response header, writing structured audit events, or translating an application-specific condition into an HTTP response.
Custom middleware should handle a cross-cutting concern. Business rules that belong to a particular use case generally belong in application services or endpoint/controller logic.
4.1 Inline custom middleware
For a small, local behavior, inline middleware is often enough.
app.Use(async (context, next) =>
{
context.Response.Headers["X-App-Name"] = "InterviewReady";
await next(context);
});
Inline middleware is quick and easy to read, but too much logic in Program.cs makes the pipeline difficult to maintain and test.
4.2 Class-based middleware using RequestDelegate
A conventional middleware class usually receives a RequestDelegate in its constructor and exposes an Invoke or InvokeAsync method that accepts HttpContext.
Step 1: Create the middleware class
using System.Diagnostics;
namespace MyApi.Middleware;
public sealed class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestTimingMiddleware> _logger;
public RequestTimingMiddleware(
RequestDelegate next,
ILogger<RequestTimingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var stopwatch = Stopwatch.StartNew();
try
{
await _next(context);
}
finally
{
stopwatch.Stop();
_logger.LogInformation(
"HTTP {Method} {Path} returned {StatusCode} in {ElapsedMs} ms",
context.Request.Method,
context.Request.Path,
context.Response.StatusCode,
stopwatch.Elapsed.TotalMilliseconds);
}
}
}
Step 2: Register it in Program.cs
using MyApi.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseMiddleware<RequestTimingMiddleware>();
app.MapControllers();
app.Run();
Call any controller endpoint. The logger records the HTTP method, path, response status code, and elapsed duration. The finally block ensures timing is logged even when downstream code throws; the exception still propagates unless an exception handler handles it.
4.3 Middleware activation and dependency injection
Conventional middleware is normally constructed when the pipeline is built. Constructor-injected dependencies are therefore generally expected to be safe for the middleware's long lifetime.
- Singleton services can be suitable if their dependencies and behavior are thread-safe.
- Scoped services such as EF Core
DbContextshould not normally be injected into a conventional middleware constructor. - If a scoped dependency is needed for each request, inject it into
InvokeAsyncor useIMiddleware.
Example of per-request method injection:
public sealed class UserContextMiddleware
{
private readonly RequestDelegate _next;
public UserContextMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(
HttpContext context,
IUserContextService userContextService)
{
await userContextService.LoadAsync(context.RequestAborted);
await _next(context);
}
}
The method-injected service is resolved for the request. Ensure the service uses the correct lifetime and does not perform unnecessary work on every request.
4.4 Using IMiddleware
IMiddleware is an alternative that lets the dependency injection container activate the middleware per request. It is useful when middleware needs scoped services through its constructor.
namespace MyApi.Middleware;
public sealed class TenantMiddleware : IMiddleware
{
private readonly ITenantResolver _tenantResolver;
private readonly ILogger<TenantMiddleware> _logger;
public TenantMiddleware(
ITenantResolver tenantResolver,
ILogger<TenantMiddleware> logger)
{
_tenantResolver = tenantResolver;
_logger = logger;
}
public async Task InvokeAsync(
HttpContext context,
RequestDelegate next)
{
var tenant = await _tenantResolver.ResolveAsync(
context.Request,
context.RequestAborted);
if (tenant is null)
{
_logger.LogWarning("No tenant could be resolved for {Path}",
context.Request.Path);
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync(
"A valid tenant is required.",
context.RequestAborted);
return;
}
context.Items["Tenant"] = tenant;
await next(context);
}
}
Register the middleware and its dependencies:
builder.Services.AddScoped<ITenantResolver, TenantResolver>();
builder.Services.AddTransient<TenantMiddleware>();
var app = builder.Build();
app.UseMiddleware<TenantMiddleware>();
The IMiddleware implementation must be registered in DI. Conventional middleware that doesn't implement IMiddleware is activated differently by UseMiddleware<T>().
Security note: Tenant resolution is not a substitute for authorization. Validate tenant identity and enforce access rules at the appropriate application boundaries. Never trust a tenant ID supplied by a client without validation.
Conventional middleware vs IMiddleware
| Topic | Conventional middleware | IMiddleware |
|---|---|---|
| Shape | Constructor takes RequestDelegate; has Invoke/InvokeAsync | Implements IMiddleware and InvokeAsync |
| Activation | Built by the middleware pipeline | Activated through DI |
| Constructor-injected scoped services | Generally unsafe due to long-lived instance | Supported when middleware is resolved within request scope |
| Registration | Usually app.UseMiddleware<T>() | Register middleware in DI and call UseMiddleware<T>() |
| Best fit | Lightweight middleware with long-lived dependencies | Middleware needing DI-managed per-request activation |
5. Correlation IDs and request observability
A correlation ID helps connect logs for a request as it travels through an application. A server can generate an ID for each request, or validate an upstream ID according to a trust policy. Treat inbound correlation values as untrusted input: validate length and allowed characters, and avoid accepting arbitrary large or control-character-containing values.
This simple example generates a fresh ID for each request:
namespace MyApi.Middleware;
public sealed class CorrelationIdMiddleware
{
public const string HeaderName = "X-Correlation-ID";
private readonly RequestDelegate _next;
private readonly ILogger<CorrelationIdMiddleware> _logger;
public CorrelationIdMiddleware(
RequestDelegate next,
ILogger<CorrelationIdMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var correlationId = Guid.NewGuid().ToString("N");
context.TraceIdentifier = correlationId;
context.Response.Headers[HeaderName] = correlationId;
using (_logger.BeginScope(new Dictionary<string, object>
{
["CorrelationId"] = correlationId
}))
{
await _next(context);
}
}
}
Register it early enough that downstream logging and middleware can use the identifier:
app.UseMiddleware<CorrelationIdMiddleware>();
The logging scope is disposed when downstream processing completes. Correlation IDs are for observability, not authentication credentials. If you need to preserve an upstream ID across services, validate it and establish a clear trust boundary.
6. Middleware order: the most important practical concept
Middleware order is not cosmetic. It changes application behavior.
A typical API pipeline might look like this:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
options.AddPolicy("FrontendPolicy", policy =>
policy.WithOrigins("https://frontend.example.com")
.AllowAnyHeader()
.AllowAnyMethod());
});
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("FrontendPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
This is illustrative: AddAuthentication() needs a real authentication scheme to authenticate users, and /error must be implemented appropriately. Modern minimal hosting can automatically insert some middleware, but understanding logical order remains important.
6.1 Exception handling should be early
Exception-handling middleware needs to wrap downstream components so it can observe exceptions thrown by them.
app.UseExceptionHandler("/error");
If exception handling is placed after the component that throws, it cannot catch exceptions that have already escaped that earlier component. Do not expose stack traces, secrets, connection strings, or internal exception details to production clients.
6.2 Routing should run before authorization when endpoint metadata is needed
Routing selects an endpoint and makes its metadata available to later middleware. Authorization can then evaluate endpoint-specific attributes and policies.
Common explicit pattern:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
With modern minimal hosting, endpoint routing is integrated into the hosting model and some placement may be inferred. Still, understanding the logical order is essential.
6.3 Authentication before authorization
- Authentication: Who is the user?
- Authorization: Is that user allowed to perform this action?
app.UseAuthentication();
app.UseAuthorization();
Reversing these calls can cause authorization to run before the user has been authenticated by the configured middleware.
6.4 CORS must be in the right place
When using routing, a common explicit order is:
app.UseRouting();
app.UseCors("FrontendPolicy");
app.UseAuthentication();
app.UseAuthorization();
CORS behavior depends on the selected policy and endpoint configuration. Configure only the origins, methods, and headers your client needs. CORS is a browser policy, not authentication or authorization.
6.5 Static files can short-circuit
UseStaticFiles() can serve a file and end processing before later middleware runs. This is often desirable for performance, but it means downstream middleware may not log or otherwise process those requests.
Place static-file middleware deliberately based on whether those requests should pass through earlier security, logging, or other middleware. Static-file middleware does not automatically make arbitrary private files safe to expose.
A useful baseline
Treat this as a baseline, not a universal recipe. Static files, response compression, forwarded headers, rate limiting, session, antiforgery, and other middleware may require additional ordering decisions.
7. Middleware and HttpContext
HttpContext represents the current HTTP request and response. Middleware commonly reads the request, sets response headers, uses request-scoped data, and observes cancellation.
| Member | Meaning |
|---|---|
context.Request | Incoming HTTP request |
context.Response | Outgoing HTTP response |
context.User | Authenticated principal, if established |
context.RequestServices | Request service provider |
context.RequestAborted | Cancellation token for the request |
context.TraceIdentifier | Identifier for this HTTP request |
context.Items | Per-request key/value storage |
context.Connection | Connection-related information |
Store data for later middleware
app.Use(async (context, next) =>
{
context.Items["RequestStartedAt"] = DateTimeOffset.UtcNow;
await next(context);
});
app.Use(async (context, next) =>
{
if (context.Items.TryGetValue("RequestStartedAt", out var value))
{
Console.WriteLine($"Request started at: {value}");
}
await next(context);
});
HttpContext.Items is intended for sharing data during one request. Do not use it as cross-request storage.
Respect request cancellation
await context.Response.WriteAsync(
"Request completed.",
context.RequestAborted);
In real code, don't blindly catch and suppress OperationCanceledException. A client disconnect or cancellation is not always an application failure; handle it according to the operation and logging policy.
8. Middleware versus filters, controllers, and services
Middleware and MVC filters are related but not interchangeable.
| Feature | Middleware | MVC filters | Controller/endpoint | Application service |
|---|---|---|---|---|
| Scope | Broad HTTP pipeline | MVC action/result execution | A specific endpoint | Application/business operation |
| Can run before routing? | Yes, depending on placement | No, requires MVC execution | No | Not by itself |
| Knows selected endpoint? | Only after routing has selected it | Works within MVC context | Yes | Usually receives explicit inputs |
| Typical responsibility | Exception handling, logging, CORS | Action-specific validation, result processing | HTTP contract and orchestration | Business rules and use cases |
| Runs for non-MVC endpoints? | If in pipeline | Generally no | Only the relevant endpoint | When invoked |
Rule of thumb: Use middleware for concerns that span many requests. Use filters for MVC-specific execution concerns. Use application services for business logic.
9. Common mistakes and how to avoid them
Mistake 1: Forgetting to call next
app.Use(async (context, next) =>
{
Console.WriteLine("The request never continues.");
// Missing: await next(context);
});
Fix: Call await next(context) unless short-circuiting is intentional.
Mistake 2: Writing the response after it has started
Once the response has started, headers and status code generally cannot be changed. Downstream middleware might already have sent response headers or body bytes.
Fix: Set status codes and headers before writing the body. Be careful when buffering or modifying response bodies.
Mistake 3: Injecting a scoped service into conventional middleware's constructor
A conventional middleware instance is typically long-lived. Capturing a scoped DbContext in its constructor can lead to lifetime errors or incorrect cross-request behavior.
Fix: Inject the service into InvokeAsync, or implement IMiddleware and register it with DI.
Mistake 4: Doing expensive work for every request
Middleware that calls a database or remote service on every request can add latency to the entire application.
Fix: Keep middleware focused, measure its cost, cache only where correctness permits, and avoid unnecessary network calls.
Mistake 5: Treating Map as endpoint routing
app.Map("/api", ...) creates a branch; app.MapGet("/api/items", handler) defines a GET endpoint.
Fix: Use the API that matches the task.
Mistake 6: Misordering authentication and authorization
Authorization often relies on the principal established by authentication.
Fix: In a typical pipeline, call UseAuthentication() before UseAuthorization().
Mistake 7: Logging sensitive data
Logging request bodies, cookies, bearer tokens, passwords, or full query strings may expose sensitive information.
Fix: Log the minimum useful data, redact secrets, and apply retention/access controls to logs.
Mistake 8: Swallowing exceptions
try
{
await _next(context);
}
catch
{
// Dangerous: request may appear successful despite failure.
}
Fix: Use centralized exception handling. If you catch an exception, handle it intentionally and return an accurate status code, or rethrow it.
Mistake 9: Assuming every request reaches the endpoint
Static files, authentication challenges, CORS preflight handling, rate limiting, and custom middleware can end the pipeline early.
Fix: When debugging, identify exactly which component short-circuited the request.
Mistake 10: Changing headers too late
Response headers become immutable after the response starts.
Fix: Set headers before downstream execution when possible, or use supported response callbacks where appropriate.
10. Testing custom middleware
Middleware can be tested through integration tests with WebApplicationFactory<TEntryPoint> or focused tests using a controlled DefaultHttpContext and a test RequestDelegate.
What to test:
- Does the middleware call the next delegate for valid requests?
- Does it short-circuit invalid requests?
- Are response headers and status codes correct?
- Does it respect cancellation?
- Does it log or propagate exceptions as intended?
- Does it behave correctly when downstream code throws?
- Does it avoid leaking request data between requests?
Example: integration-test shape
The exact setup depends on your application's entry point and test project.
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
public sealed class HealthEndpointTests
: IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client;
public HealthEndpointTests(WebApplicationFactory<Program> factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task HealthEndpoint_ReturnsSuccess()
{
using var response = await _client.GetAsync("/health");
Assert.True(response.IsSuccessStatusCode);
}
}
For top-level statements, you may need to expose Program to the test project by adding public partial class Program { } at the end of the application entry-point file, depending on project setup.
11. Mini-project: request timing and correlation
Build a small API that adds a correlation ID to each response, logs request duration and status code, exposes a health endpoint, uses centralized exception handling, and keeps middleware registration easy to understand.
Suggested folder structure
MiddlewareDemo/
├── Middleware/
│ ├── CorrelationIdMiddleware.cs
│ └── RequestTimingMiddleware.cs
├── Program.cs
└── MiddlewareDemo.csproj
Program.cs
using MiddlewareDemo.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.UseMiddleware<CorrelationIdMiddleware>();
app.UseMiddleware<RequestTimingMiddleware>();
app.MapGet("/health", () => Results.Ok(new
{
status = "healthy",
checkedAtUtc = DateTimeOffset.UtcNow
}));
app.MapGet("/slow", async (CancellationToken cancellationToken) =>
{
await Task.Delay(TimeSpan.FromMilliseconds(250), cancellationToken);
return Results.Ok(new
{
message = "Completed",
checkedAtUtc = DateTimeOffset.UtcNow
});
});
app.Run();
// Add this only if the test project needs to reference the generated entry point.
public partial class Program { }
Expected behavior
GET /healthreturns a healthy status.GET /slowwaits approximately 250 milliseconds unless cancelled.- Each response includes
X-Correlation-ID. - Request timing is written to the configured logger.
- Unhandled exceptions are handled by the configured exception handler and Problem Details services where applicable.
Practice extensions
- Add middleware that rejects requests missing
X-Client-Version. - Add a request-size limit appropriate to your API.
- Write integration tests for the correlation ID header.
- Add a structured log scope with the correlation ID.
- Confirm that health checks and error responses are logged as expected.
- Decide whether static-file requests should pass through timing middleware.
- Add custom exception mapping for a known application exception without exposing internal details.
12. Performance and security checklist
Performance
- Keep middleware small and focused.
- Avoid synchronous blocking operations such as
.Resultor.Wait(). - Use asynchronous APIs for I/O.
- Avoid unnecessary allocations in high-volume middleware.
- Don't read or buffer large request/response bodies without a clear requirement and limits.
- Measure latency before optimizing.
- Use structured logging and appropriate log levels.
- Ensure shared state is thread-safe.
Security
- Place authentication and authorization correctly.
- Do not rely on CORS as access control.
- Validate untrusted headers before using them.
- Never log credentials, access tokens, or sensitive payloads.
- Use exception handling that avoids exposing internal details in production.
- Apply request-size and rate limits appropriate to the threat model.
- Ensure branch-specific middleware doesn't accidentally bypass required protections.
- Treat
HttpContext.Itemsvalues as application-internal data, not automatically trusted user identity.
13. Frequently Asked Questions
What is middleware in ASP.NET Core?
Middleware is a component in the HTTP request pipeline that can inspect or modify requests and responses, call the next component, or short-circuit processing.
What is the difference between Use, Run, and Map?
Use registers middleware that can invoke the next component, Run registers a terminal request delegate, and Map creates a pipeline branch based on a matching request path.
How do you write custom middleware in ASP.NET Core?
Create a class that accepts RequestDelegate and exposes InvokeAsync(HttpContext), then register it with app.UseMiddleware<T>(). Alternatively, implement IMiddleware and register the middleware in dependency injection.
Why does middleware order matter in ASP.NET Core?
Middleware order determines which components run and what information is available. For example, authentication typically runs before authorization, and exception handling must wrap downstream components to handle their exceptions.
15. Multiple-choice questions
Q1. Which API is designed to register a terminal request delegate?
A. Use
B. Run
C. MapGet
D. UseRouting
Answer: B. Run registers a terminal delegate that does not receive a next delegate.
Q2. Which order is normally correct for authentication and authorization?
A. Authorization, then authentication
B. Authentication, then authorization
C. Either order always works
D. Neither belongs in middleware
Answer: B. Authentication establishes the principal that authorization can evaluate.
Q3. What happens if middleware doesn't call next?
A. ASP.NET Core calls it automatically
B. The request is always retried
C. Downstream processing is skipped
D. The application always crashes
Answer: C. The middleware short-circuits the pipeline if it completes a response without invoking the next delegate.
Q4. Which API creates a path-based middleware branch?
A. Map
B. MapGet
C. AddScoped
D. UseAuthorization
Answer: A. Map branches the pipeline based on a matching path prefix.
Q5. Why is a scoped DbContext generally unsuitable for constructor injection into conventional middleware?
A. It cannot execute queries
B. Middleware instances are typically long-lived
C. It only works in controllers
D. It cannot be resolved by DI
Answer: B. The middleware's lifetime can exceed the request scope, so capturing a scoped service is unsafe.
Q6. Which property exposes request cancellation?
A. context.ResponseAborted
B. context.RequestAborted
C. context.UserCancelled
D. context.ConnectionClosed
Answer: B. RequestAborted is the cancellation token associated with the request.
Q7. What is HttpContext.Items primarily for?
A. Global caching across users
B. Persistent database storage
C. Sharing values during one request
D. Storing application configuration
Answer: C. Items is per-request storage.
Q8. What is the primary role of exception-handling middleware?
A. Authenticate users
B. Catch and handle downstream exceptions
C. Match routes
D. Serve static files
Answer: B. It wraps downstream processing and can produce a controlled error response when exceptions occur.
Q9. Which statement about CORS is correct?
A. CORS replaces authorization
B. CORS is an authentication scheme
C. CORS controls browser cross-origin access; it does not secure an API by itself
D. CORS encrypts HTTP traffic
Answer: C. APIs still need appropriate authentication, authorization, and transport security.
Q10. What is the difference between app.Run() and app.Run(context => ...)?
A. There is no difference
B. The first starts the host; the second adds terminal middleware
C. The first adds a controller; the second enables routing
D. The first configures authentication
Answer: B. They are different overloads used for different purposes.
16. Quick revision cheat sheet
| Concept | Remember |
|---|---|
| Middleware | Component in the HTTP request pipeline |
| Registration order | Controls inbound execution order |
Code before next | Runs on the way in |
Code after next | Runs on the way out |
Use | Can continue or short-circuit |
Run | Terminal request delegate |
Map | Path-based pipeline branch |
MapGet | Registers a GET endpoint |
RequestDelegate | Task-returning delegate that accepts HttpContext |
HttpContext | Current request/response context |
HttpContext.Items | Data shared during one request |
RequestAborted | Request cancellation token |
| Conventional middleware | Usually constructed while pipeline is built |
IMiddleware | Activated through DI |
| Authentication | Establishes user identity |
| Authorization | Evaluates access permission |
| Exception handler | Should wrap components whose exceptions it must handle |
Revision checklist
- I can explain the request/response pipeline.
- I can trace middleware before and after
next. - I can explain
Use,Run, andMap. - I know the difference between
MapandMapGet. - I can create class-based custom middleware.
- I understand conventional middleware and
IMiddleware. - I know why scoped dependencies require care.
- I understand why exception handling, routing, authentication, and authorization are order-sensitive.
- I know how to test middleware.
- I can identify short-circuiting and response-started bugs.
17. Final takeaways
- Middleware forms the ordered HTTP request pipeline in ASP.NET Core.
- Middleware can run before and after downstream processing.
Usecan call the next component,Runregisters a terminal delegate, andMapcreates a path-based branch.- Custom middleware is best suited to cross-cutting concerns, not domain-specific business rules.
- Be careful with dependency injection lifetimes, response-started behavior, exceptions, and sensitive logging.
- Middleware order determines what information is available and which components run.
- Learn to trace the pipeline; this skill makes many ASP.NET Core debugging and interview questions much easier.
Further reading
- ASP.NET Core Middleware documentation
- Write custom ASP.NET Core middleware
- ASP.NET Core fundamentals
- ASP.NET Core routing
- ASP.NET Core error handling
Last updated 10/25/2026
Your notes
Sign in to save personal notes on this topic — they'll sync across your devices.
Was this tutorial helpful?
Help us create more free learning resources. Learn more
