Middleware in ASP.NET Core: 25 Interview Questions and Answers
Prepare for ASP.NET Core middleware interviews with 25 practical questions covering the request pipeline, middleware execution order, custom middleware, exception handling, branching, authentication, authorization, and performance.
Middleware in ASP.NET Core: 25 Interview Questions and Answers
Middleware is one of the most frequently discussed topics in ASP.NET Core interviews. It helps developers understand how HTTP requests enter an application, pass through different components, and produce responses.
This guide covers middleware from fundamental concepts to advanced implementation details, with practical C# examples and common interview follow-up questions.
1. What Is Middleware in ASP.NET Core?
Answer:
Middleware is a component in the ASP.NET Core request pipeline that processes HTTP requests and responses.
A middleware component can:
- Inspect or modify an incoming HTTP request.
- Pass the request to the next middleware.
- Execute logic after the next middleware completes.
- Modify the HTTP response.
- Stop the pipeline and return a response without calling the next component.
For example, an application might use middleware for logging, authentication, exception handling, and routing.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
Console.WriteLine("Before request processing");
await next(context);
Console.WriteLine("After request processing");
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from ASP.NET Core!");
});
app.Run();When a request reaches the application, the first middleware executes. It calls the next component, which eventually writes the response. Once the downstream processing completes, the first middleware resumes and executes its remaining code.
Real-life example: Middleware works like security and reception checkpoints in an office. Each checkpoint can inspect a visitor, pass them to the next checkpoint, or stop them from proceeding.
Interview insight: Middleware can execute both before and after downstream components. This makes it useful for cross-cutting concerns such as logging, timing, and exception handling.
2. What Is the ASP.NET Core Request Pipeline?
Answer:
The request pipeline is the sequence of middleware components through which an HTTP request travels before a response is returned to the client.
Developers configure this pipeline in Program.cs using methods such as Use, Run, and Map.
Example:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
Console.WriteLine("Middleware 1 - Before");
await next(context);
Console.WriteLine("Middleware 1 - After");
});
app.Use(async (context, next) =>
{
Console.WriteLine("Middleware 2 - Before");
await next(context);
Console.WriteLine("Middleware 2 - After");
});
app.Run(async context =>
{
Console.WriteLine("Terminal middleware");
await context.Response.WriteAsync("Hello World");
});
app.Run();The execution order is:
Incoming Request
|
v
Middleware 1 - Before
|
v
Middleware 2 - Before
|
v
Terminal Middleware
|
v
Middleware 2 - After
|
v
Middleware 1 - After
|
v
HTTP ResponseThe console output is:
Middleware 1 - Before
Middleware 2 - Before
Terminal middleware
Middleware 2 - After
Middleware 1 - AfterThis behavior is often described as forward execution for the request and reverse execution for the response.
Interview insight: The order of middleware registration matters because middleware executes in the order it is added, while code after await next(context) executes in reverse order as the call stack unwinds.
3. What Are the Main Responsibilities of Middleware?
Answer:
Middleware is primarily used to implement functionality that applies across multiple endpoints or throughout the HTTP request lifecycle.
Common responsibilities include:
| Responsibility | Example |
|---|---|
| Logging | Record request duration and status code |
| Exception handling | Convert unhandled exceptions into appropriate HTTP responses |
| Authentication | Identify the caller |
| Authorization | Enforce access policies |
| Routing | Match incoming requests to endpoints |
| CORS | Apply cross-origin access policies |
| HTTPS redirection | Redirect HTTP requests to HTTPS |
| Static files | Serve CSS, JavaScript, and image files |
| Response compression | Reduce response size |
| Rate limiting | Restrict excessive requests |
Example of simple request logging:
app.Use(async (context, next) =>
{
Console.WriteLine(
$"Request: {context.Request.Method} {context.Request.Path}");
await next(context);
Console.WriteLine(
$"Response status: {context.Response.StatusCode}");
});Middleware helps avoid repeating the same logic in every controller or endpoint.
Important distinction: Middleware is appropriate for HTTP pipeline concerns. Business rules, such as calculating an order discount, generally belong in application or domain services instead.
4. What Is the Difference Between Use, Run, and Map?
Answer:
These methods configure different behaviors in the request pipeline.
| Method | Purpose | Calls the next middleware? |
|---|---|---|
Use | Adds middleware that can execute logic before and after downstream processing | Yes, when explicitly invoked |
Run | Adds terminal middleware that ends the current pipeline | No |
Map | Creates a separate pipeline branch based on a matching request path | Not automatically from the branch delegate |
Using Use
app.Use(async (context, next) =>
{
Console.WriteLine("Before");
await next(context);
Console.WriteLine("After");
});Using Run
app.Run(async context =>
{
await context.Response.WriteAsync("Request completed");
});This terminal middleware does not call another middleware.
Using Map
app.Map("/admin", adminApp =>
{
adminApp.Run(async context =>
{
await context.Response.WriteAsync("Admin branch");
});
});Requests matching the /admin path branch enter that pipeline. For example, /admin/users can enter the branch, and the branch receives the remaining path through Request.Path, while the matched prefix is available through Request.PathBase.
Common interview trap: Map here means path-based pipeline branching, not endpoint routing through MapGet, MapPost, or MapControllers.
5. Why Is Middleware Execution Order Important?
Answer:
Middleware order determines which components can inspect requests, modify responses, and make decisions before downstream processing occurs.
Consider authentication and authorization:
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();Authentication should run before authorization because authorization generally depends on the authenticated user's identity and claims.
Exception handling should normally be early in the pipeline so that it can catch exceptions thrown by downstream middleware and endpoints.
A simplified production-oriented arrangement is:
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();This is an illustrative arrangement, not a universal template. For example, static file placement, CORS, rate limiting, and endpoint-specific requirements can affect the correct ordering.
Interview insight: Explain the reason behind the order rather than memorizing a single list. For example, authorization needs the correct user identity, and exception handling must wrap the components whose exceptions it should handle.
6. What Happens If Middleware Does Not Call next?
Answer:
If middleware does not invoke the next middleware, the remaining downstream pipeline is skipped for that request.
This behavior is called short-circuiting the pipeline.
Example:
app.Use(async (context, next) =>
{
if (!context.Request.Headers.ContainsKey("X-Client-Id"))
{
context.Response.StatusCode =
StatusCodes.Status400BadRequest;
await context.Response.WriteAsync(
"Missing X-Client-Id header");
return;
}
await next(context);
});If the header is missing, the middleware returns a 400 Bad Request response without invoking the next component.
Typical use cases include:
- Rejecting invalid requests.
- Blocking unauthorized access.
- Returning cached responses.
- Handling requests that do not require downstream processing.
Common mistake: Forgetting to call next unintentionally can make endpoints unreachable. Also, do not call next more than once for the same request unless a very deliberate design supports it; multiple downstream executions can cause duplicate work and invalid response behavior.
7. What Is Custom Middleware, and When Should You Create It?
Answer:
Custom middleware is middleware that developers implement to satisfy application-specific requirements.
You should create custom middleware when the logic belongs in the HTTP request pipeline and applies to multiple endpoints or needs to wrap downstream execution.
Examples include:
- Request correlation IDs.
- Centralized request logging.
- Custom request validation.
- Timing HTTP requests.
- Adding common response headers.
A custom middleware class typically receives a RequestDelegate in its constructor and implements an InvokeAsync method.
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 = System.Diagnostics.Stopwatch.StartNew();
try
{
await _next(context);
}
finally
{
stopwatch.Stop();
_logger.LogInformation(
"Request {Method} {Path} took {ElapsedMs} ms",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds);
}
}
}Register it:
app.UseMiddleware<RequestTimingMiddleware>();The finally block ensures timing is logged even if downstream processing throws an exception, provided execution reaches the middleware's try block.
Interview insight: Custom middleware is best for cross-cutting HTTP concerns. If the requirement is specific to one business operation, a service or endpoint filter may be a better fit.
8. How Do You Write Inline Middleware Using app.Use?
Answer:
Inline middleware is defined directly in Program.cs using a delegate rather than a separate class.
Example:
app.Use(async (context, next) =>
{
var startTime = DateTime.UtcNow;
await next(context);
var elapsed = DateTime.UtcNow - startTime;
Console.WriteLine(
$"Request completed in {elapsed.TotalMilliseconds} ms");
});The context parameter represents the current HttpContext, while next represents the downstream middleware.
Inline middleware is useful for small, simple pieces of logic.
For larger implementations, prefer a dedicated middleware class because it is easier to test, maintain, and organize.
Common mistake: Performing substantial business logic inside Program.cs can make the application's composition root difficult to understand.
9. What Is the Difference Between Inline and Class-Based Middleware?
Answer:
Both approaches can participate in the same request pipeline. The main difference is how the middleware is structured.
| Feature | Inline middleware | Class-based middleware |
|---|---|---|
| Definition | Delegate in Program.cs | Separate C# class |
| Best suited for | Small, simple logic | Reusable or complex logic |
| Testability | Can be harder to isolate | Easier to unit test |
| Dependency injection | Supported through the delegate and application services | Supported through constructor and method injection patterns |
| Maintainability | Can become difficult in large applications | Usually better for substantial logic |
Inline example:
app.Use(async (context, next) =>
{
context.Response.Headers["X-App-Name"] = "InterviewReady";
await next(context);
});Class-based example:
public sealed class AppHeaderMiddleware
{
private readonly RequestDelegate _next;
public AppHeaderMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
context.Response.Headers["X-App-Name"] =
"InterviewReady";
await _next(context);
}
}Registration:
app.UseMiddleware<AppHeaderMiddleware>();Interview insight: Choose the simplest structure that remains readable and testable. A separate class is not automatically better for a one-line middleware operation.
10. What Is the Difference Between Map and MapWhen?
Answer:
Both methods can branch the middleware pipeline, but they use different matching rules.
Mapbranches based on a request path prefix.MapWhenbranches based on a predicate that receives theHttpContext.
Example using Map
app.Map("/reports", reportsApp =>
{
reportsApp.Run(async context =>
{
await context.Response.WriteAsync("Reports branch");
});
});Requests under /reports enter the branch.
Example using MapWhen
app.MapWhen(
context => context.Request.Query.ContainsKey("debug"),
debugApp =>
{
debugApp.Run(async context =>
{
await context.Response.WriteAsync("Debug branch");
});
});A request such as /products?debug=true enters the debug branch because the query contains the debug key.
Important: A query-key check is only an example of branching, not an authorization mechanism. Never use an easily supplied query parameter as proof that a caller is permitted to access protected functionality.
Interview insight: Use Map for path-based separation and MapWhen when branching depends on arbitrary request properties.
11. What Is the Difference Between Use and Map in Routing?
Answer:
The distinction is that Use adds middleware to the current pipeline, whereas Map creates a path-based branch.
For example:
app.Use(async (context, next) =>
{
Console.WriteLine("Common middleware");
await next(context);
});
app.Map("/health-check", healthApp =>
{
healthApp.Run(async context =>
{
await context.Response.WriteAsync("Healthy");
});
});The common middleware can run for requests entering the pipeline before the branch. A matching /health-check request then enters the branch.
By contrast, endpoint routing uses methods such as:
app.MapGet("/products", () =>
{
return Results.Ok(new[] { "Laptop", "Phone" });
});MapGet registers an HTTP GET endpoint; it does not mean the same thing as IApplicationBuilder.Map.
Interview follow-up: If asked about Map, clarify whether the interviewer means path-based middleware branching or endpoint mapping.
12. What Is the Difference Between Middleware and Filters in ASP.NET Core MVC?
Answer:
Middleware and MVC filters can both execute logic around request processing, but they operate at different levels.
Middleware operates in the application-wide HTTP pipeline. MVC filters operate within the MVC or controller-based endpoint execution pipeline.
| Feature | Middleware | MVC filters |
|---|---|---|
| Execution level | HTTP request pipeline | MVC action execution pipeline |
| Scope | Can apply across the application | Applies to MVC actions or controllers, depending on registration |
| Access to action arguments | Not inherently available | Action filters can inspect action arguments |
| Typical uses | Exception handling, logging, authentication, routing | Action validation, action-specific logging, result manipulation |
| Works outside MVC | Yes | No, MVC filters are specific to MVC |
Example of an action filter:
public sealed class LogActionFilter : IActionFilter
{
private readonly ILogger<LogActionFilter> _logger;
public LogActionFilter(ILogger<LogActionFilter> logger)
{
_logger = logger;
}
public void OnActionExecuting(ActionExecutingContext context)
{
_logger.LogInformation("MVC action is executing");
}
public void OnActionExecuted(ActionExecutedContext context)
{
_logger.LogInformation("MVC action has executed");
}
}Register it globally:
builder.Services.AddControllers(options =>
{
options.Filters.Add<LogActionFilter>();
});Register the filter type with dependency injection if required by the chosen registration pattern.
Interview insight: Choose middleware for HTTP-level cross-cutting behavior and filters when you need access to MVC-specific concepts such as action arguments, action results, or MVC execution stages.
13. How Does Exception-Handling Middleware Work?
Answer:
Exception-handling middleware catches exceptions that occur in downstream processing and can produce a consistent error response.
ASP.NET Core provides built-in exception-handling support through UseExceptionHandler.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}For an API, you can also configure an exception handler that returns a structured JSON response.
Example using a custom middleware:
public sealed class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError(
ex,
"An unhandled exception occurred.");
if (context.Response.HasStarted)
{
throw;
}
context.Response.Clear();
context.Response.StatusCode =
StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new
{
message = "An unexpected error occurred."
});
}
}
}Register it early in the pipeline:
app.UseMiddleware<ExceptionHandlingMiddleware>();This example deliberately avoids returning the exception message or stack trace to the client.
Important considerations:
- Do not expose internal exception details in production responses.
- Log exceptions with appropriate context.
- If the response has already started, replacing it with a new error response may not be possible.
- Exception handling cannot catch failures that occur before the middleware is entered or failures outside its downstream execution scope.
Interview insight: A try-catch in a controller handles errors within that controller's scope. Exception middleware centralizes handling for downstream request processing across many endpoints.
14. How Does Middleware Differ from Authentication and Authorization Services?
Answer:
Authentication and authorization are related but different responsibilities.
- Authentication determines who the caller is.
- Authorization determines what the caller is allowed to do.
ASP.NET Core provides authentication and authorization middleware that integrate with registered authentication handlers and authorization policies.
Example:
builder.Services.AddAuthentication()
.AddJwtBearer(options =>
{
options.Authority = "https://identity.example.com";
options.Audience = "products-api";
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/profile", (ClaimsPrincipal user) =>
{
return Results.Ok(new
{
Name = user.Identity?.Name
});
}).RequireAuthorization();
app.Run();This is an illustrative JWT configuration. The identity provider, issuer, audience, signing keys, and token validation settings must match the actual environment.
Authentication middleware establishes the request's identity when valid credentials are supplied. Authorization middleware evaluates the configured access requirements.
Common mistake: Calling UseAuthorization without the necessary authorization services or placing authorization before authentication can lead to configuration errors or incorrect behavior.
Interview insight: Authentication answers "Who are you?" Authorization answers "What are you allowed to access?"
15. Why Must Authentication Run Before Authorization?
Answer:
Authorization commonly evaluates the identity and claims established during authentication.
Consider this configuration:
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();The authentication middleware attempts to authenticate the request using the configured scheme. The authorization middleware then evaluates endpoint policies against the available user identity and claims.
If the order is reversed, authorization may evaluate the request before authentication has established the expected identity.
For example, an endpoint might require an administrator role:
app.MapGet("/admin", () => "Admin area")
.RequireAuthorization(policy =>
policy.RequireRole("Admin"));The role claim must be correctly established and validated for the authorization policy to grant access.
Interview insight: Authentication and authorization should not be confused with one another. A successfully authenticated user is not automatically authorized to access every endpoint.
16. What Is the Difference Between RequestDelegate and HttpContext?
Answer:
HttpContext represents the current HTTP request and response, while RequestDelegate represents a function that processes an HTTP context asynchronously.
The delegate has this conceptual signature:
public delegate Task RequestDelegate(HttpContext context);A middleware component receives a RequestDelegate representing the next component in the pipeline.
Example:
public sealed class SimpleMiddleware
{
private readonly RequestDelegate _next;
public SimpleMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
context.Response.Headers["X-Processed"] = "true";
await _next(context);
}
}Here:
_nextrepresents the downstream pipeline.context.Requestprovides request information.context.Responseprovides response functionality.context.Userrepresents the current principal.context.RequestServicesexposes the request's service provider.
Interview insight: RequestDelegate connects middleware components; HttpContext carries the information they process.
17. What Is the Difference Between Invoke and InvokeAsync in Custom Middleware?
Answer:
ASP.NET Core middleware convention supports an instance method named either Invoke or InvokeAsync, provided it has the expected signature and returns a Task.
Both methods can serve as the middleware entry point.
Example:
public sealed class SampleMiddleware
{
private readonly RequestDelegate _next;
public SampleMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
await _next(context);
}
}The Async suffix follows standard C# naming conventions for asynchronous methods.
The method must accept an HttpContext parameter, return a Task, and satisfy the middleware activation requirements. Additional parameters can be resolved from dependency injection when supported by the middleware activation mechanism.
Interview insight: The name alone does not determine whether middleware is asynchronous. The method's return type and implementation determine its asynchronous behavior.
18. What Is the Difference Between Conventional and Factory-Activated Middleware?
Answer:
ASP.NET Core supports middleware activation patterns that affect how middleware instances are created and how dependencies are supplied.
Conventional middleware
Conventional middleware is commonly registered using UseMiddleware<T>() and has a constructor that receives RequestDelegate.
public sealed class ConventionalMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ConventionalMiddleware> _logger;
public ConventionalMiddleware(
RequestDelegate next,
ILogger<ConventionalMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
_logger.LogInformation("Processing request");
await _next(context);
}
}The middleware instance is generally created when the pipeline is built and reused across requests.
Factory-activated middleware
IMiddleware allows middleware activation through dependency injection.
public sealed class FactoryActivatedMiddleware : IMiddleware
{
private readonly ILogger<FactoryActivatedMiddleware> _logger;
public FactoryActivatedMiddleware(
ILogger<FactoryActivatedMiddleware> logger)
{
_logger = logger;
}
public async Task InvokeAsync(
HttpContext context,
RequestDelegate next)
{
_logger.LogInformation("Processing request");
await next(context);
}
}Register it:
builder.Services.AddTransient<FactoryActivatedMiddleware>();
var app = builder.Build();
app.UseMiddleware<FactoryActivatedMiddleware>();The IMiddleware implementation is resolved from dependency injection for each request, according to its registered service lifetime.
Interview insight: The important difference is the activation model, particularly how dependencies and service lifetimes are handled.
19. How Do You Inject a Scoped Service into Middleware?
Answer:
A scoped service is normally created once per request in a web application using the default dependency injection container.
Conventional middleware instances are generally created at application startup and reused across requests. Therefore, directly injecting a scoped service into the constructor of conventional middleware is not appropriate.
Consider a scoped service:
public interface IRequestAuditService
{
Task RecordAsync(string path);
}
public sealed class RequestAuditService : IRequestAuditService
{
private readonly ILogger<RequestAuditService> _logger;
public RequestAuditService(
ILogger<RequestAuditService> logger)
{
_logger = logger;
}
public Task RecordAsync(string path)
{
_logger.LogInformation(
"Auditing request to {Path}", path);
return Task.CompletedTask;
}
}Register it:
builder.Services.AddScoped<IRequestAuditService, RequestAuditService>();Inject it into the conventional middleware's InvokeAsync method:
public sealed class AuditMiddleware
{
private readonly RequestDelegate _next;
public AuditMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(
HttpContext context,
IRequestAuditService auditService)
{
await auditService.RecordAsync(context.Request.Path);
await _next(context);
}
}Register the middleware:
app.UseMiddleware<AuditMiddleware>();The scoped service can be resolved for the current request.
Alternatively, use IMiddleware with a suitable DI lifetime when constructor injection of scoped dependencies is preferable.
Common mistake: Injecting a scoped DbContext directly into the constructor of conventional middleware can cause a lifetime validation exception or accidentally retain request-scoped dependencies too long.
20. Why Should Middleware Be Thread-Safe?
Answer:
Conventional middleware instances are generally reused across multiple HTTP requests. Multiple requests can execute the same middleware instance concurrently.
If middleware stores request-specific mutable information in instance fields, one request can overwrite another request's data.
Incorrect example:
public sealed class UnsafeMiddleware
{
private readonly RequestDelegate _next;
private string? _currentPath;
public UnsafeMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
_currentPath = context.Request.Path;
await _next(context);
Console.WriteLine(_currentPath);
}
}Two concurrent requests can overwrite _currentPath, causing incorrect logging.
Correct approach:
public sealed class SafeMiddleware
{
private readonly RequestDelegate _next;
public SafeMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var currentPath = context.Request.Path;
await _next(context);
Console.WriteLine(currentPath);
}
}The local variable belongs to the individual invocation rather than shared middleware state.
Interview insight: Thread safety is not just about locks. Often, the best solution is to avoid shared mutable state entirely.
21. What Is the Difference Between Middleware and Endpoint Filters?
Answer:
Endpoint filters are designed for endpoint-level behavior, particularly with Minimal APIs. Middleware operates at the HTTP pipeline level.
| Feature | Middleware | Endpoint filters |
|---|---|---|
| Scope | Broad HTTP pipeline | Selected endpoints |
| Main purpose | Cross-cutting HTTP concerns | Endpoint-specific processing |
| Access to endpoint arguments | Not inherently available | Can inspect endpoint arguments |
| Typical use | Logging, exception handling, authentication | Validation, argument transformation, endpoint timing |
Example endpoint filter:
public sealed class TimingFilter : IEndpointFilter
{
private readonly ILogger<TimingFilter> _logger;
public TimingFilter(ILogger<TimingFilter> logger)
{
_logger = logger;
}
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context,
EndpointFilterDelegate next)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
try
{
return await next(context);
}
finally
{
stopwatch.Stop();
_logger.LogInformation(
"Endpoint executed in {ElapsedMs} ms",
stopwatch.ElapsedMilliseconds);
}
}
}Apply it to a Minimal API endpoint:
app.MapGet("/products/{id:int}", (int id) =>
{
return Results.Ok(new { Id = id });
})
.AddEndpointFilter<TimingFilter>();The filter must be registered with dependency injection if required by the chosen filter activation pattern.
Interview insight: Middleware is ideal for behavior shared across many requests. Endpoint filters are useful when the logic needs access to the arguments and execution of a particular endpoint.
22. How Does Middleware Handle HTTP Responses and Response Headers?
Answer:
Middleware can inspect or modify response headers and status codes, but the response has a lifecycle that must be respected.
For example:
app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
context.Response.Headers["X-Application"] =
"DotNetInterviewReady";
return Task.CompletedTask;
});
await next(context);
});OnStarting registers a callback that executes before the response headers are sent. This is useful when downstream middleware might otherwise start the response before the outer middleware regains control.
A simpler example is:
app.Use(async (context, next) =>
{
await next(context);
if (!context.Response.HasStarted)
{
context.Response.Headers["X-Processed"] = "true";
}
});However, checking HasStarted and then setting headers is not an atomic operation. In general, use OnStarting when you need to ensure a header is added before the response begins.
Once the response has started, headers and the status code generally cannot be changed.
Interview insight: Middleware can execute after downstream processing, but that does not guarantee that the response is still mutable.
23. What Is Short-Circuiting in Middleware, and How Does It Improve Performance?
Answer:
Short-circuiting means returning a response without invoking downstream middleware.
For example, an application might handle a lightweight health endpoint directly:
app.MapGet("/health", () =>
{
return Results.Ok(new { Status = "Healthy" });
});Endpoint routing can execute this endpoint without invoking downstream middleware registered after endpoint execution in a typical pipeline.
A custom middleware can also short-circuit:
app.Use(async (context, next) =>
{
if (context.Request.Path == "/maintenance")
{
context.Response.StatusCode =
StatusCodes.Status503ServiceUnavailable;
await context.Response.WriteAsync(
"Service temporarily unavailable");
return;
}
await next(context);
});Short-circuiting can avoid unnecessary work when the response can be determined early.
However, not every request should be handled this way. Skipping downstream middleware may also skip logging, authentication, routing, or other required behavior depending on the pipeline structure.
Interview insight: Short-circuiting improves performance only when it safely avoids unnecessary work. Security and observability requirements must still be considered.
24. What Are Common Middleware Mistakes in ASP.NET Core?
Answer:
Several mistakes can cause incorrect responses, security issues, or performance problems.
Mistake 1: Incorrect middleware order
Incorrect:
app.UseAuthorization();
app.UseAuthentication();Correct:
app.UseAuthentication();
app.UseAuthorization();Authentication should normally precede authorization.
Mistake 2: Forgetting to call the next middleware
app.Use(async (context, next) =>
{
Console.WriteLine("Request received");
// Downstream processing never occurs.
});If the middleware does not produce a response and does not call next, the request may never reach its intended endpoint.
Mistake 3: Injecting scoped services into conventional middleware constructors
Conventional middleware instances are generally reused. Inject scoped dependencies through InvokeAsync or use factory-activated middleware where appropriate.
Mistake 4: Exposing exception details
Returning stack traces or raw database errors to clients can reveal sensitive implementation details.
Mistake 5: Modifying headers after the response starts
Once response headers have been sent, changing them is generally too late.
Mistake 6: Storing request data in shared instance fields
This can introduce race conditions when multiple requests execute concurrently.
Mistake 7: Performing expensive synchronous operations
Blocking I/O in middleware can reduce scalability. Prefer asynchronous APIs for database, file, and network operations.
Mistake 8: Logging sensitive information
Avoid logging passwords, access tokens, authentication cookies, and unnecessary personal data.
Interview insight: Strong middleware implementations consider execution order, service lifetimes, asynchronous processing, response state, and security together.
25. How Would You Design a Production-Ready Middleware Pipeline?
Answer:
A production pipeline should provide the necessary error handling, transport security, routing, authentication, authorization, and endpoint execution in an order that matches the application's requirements.
For example:
using Microsoft.AspNetCore.Authentication.JwtBearer;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddAuthentication(
JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://identity.example.com";
options.Audience = "products-api";
});
builder.Services.AddAuthorization();
builder.Services.AddCors(options =>
{
options.AddPolicy("Frontend", policy =>
{
policy
.WithOrigins("https://example.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("Frontend");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();This is a starting point, not a complete security configuration for every production API.
Key considerations include:
- Exception handling: Handle unhandled downstream exceptions and avoid exposing internal details.
- HTTPS: Use HTTPS and configure transport security appropriately.
- Routing: Ensure endpoint matching is configured correctly.
- CORS: Configure trusted browser origins when cross-origin access is required.
- Authentication: Validate credentials using the intended authentication scheme.
- Authorization: Enforce policies and endpoint permissions.
- Observability: Add structured logging, tracing, and request metrics where appropriate.
- Performance: Avoid unnecessary synchronous blocking and redundant processing.
- Security: Protect sensitive information and ensure every endpoint has the intended access rules.
The precise ordering can vary. For example, applications using rate limiting, static files, output caching, or endpoint-specific CORS policies may require additional ordering decisions.
Interview insight: A senior developer should be able to explain why each middleware is present, what it protects, and which components must execute before or after it.
Key Takeaways
- Middleware components form the HTTP request pipeline in ASP.NET Core.
- Requests normally execute middleware in registration order; code after
await next(context)runs as downstream processing completes. Useadds middleware,Runadds terminal middleware, andMapcreates a path-based branch.- Middleware can short-circuit a request by not invoking the next component.
- Middleware order is critical, especially for exception handling, routing, authentication, and authorization.
- Conventional middleware instances are generally reused, so avoid storing request-specific mutable state in instance fields.
- Scoped dependencies should not be directly captured by conventional middleware constructors.
- Use custom middleware for cross-cutting HTTP concerns, MVC filters for MVC-specific execution, and endpoint filters for endpoint-specific processing.
- Response headers cannot generally be modified after the response starts.
- Production middleware should be secure, asynchronous where appropriate, observable, and carefully ordered.
