ASP.NET Core Interview Questions for Senior Developers — The Middleware Pipeline, DI Lifetimes, Kestrel & Auth (Deep Answers)
30 senior ASP.NET Core interview questions with deep answers and real production code: the middleware pipeline, DI lifetimes, Kestrel, hosting, and auth.
- Author
- Randhir Jassal
- Published
- Reading time
- 19 min read
- Views
- 74 views
Junior ASP.NET Core interviews ask "what is middleware." Senior interviews ask why your
UseAuthorizationran before routing and silently allowed an anonymous request through, or why a singleton that took aDbContextcorrupted data across tenants. The framework is easy to use and easy to misuse in ways that only show up in production — under load, across tenants, at 3am. This guide is 30 questions on the parts that actually separate seniors: the request pipeline, DI & lifetimes, hosting & performance, and auth & APIs.
Each answer is a short answer you could say in one breath, a deep dive into the mechanism with code, and the senior signal the interviewer is listening for. Every sample is from Mattrx — a real multi-tenant marketing-analytics SaaS on .NET 9 / ASP.NET Core, ~3,200 req/sec peak, Azure SQL + Redis, OAuth via Entra ID. No Foo and Bar.
How to use this guide
Read the deep dive even when the short answer is obvious — seniority is in the why and the failure mode. The blocks build on each other. If you can explain each code comment out loud, you're ready.
Block A — the request pipeline & middleware
1. How does the middleware pipeline work, and why does order matter?
Short answer: Middleware is a chain of components, each of which can act on the request, call next() to pass control down, and act on the response as the chain unwinds. Order is everything: a component only sees what the components before it let through.
Deep dive: It's a nested set of delegates. Auth must run before the endpoint (so the endpoint sees an authenticated user); exception handling must be first (so it wraps everything below).
Request
|
v
[ ExceptionHandler ] -> [ HTTPS ] -> [ Routing ] -> [ AuthN ] -> [ AuthZ ] -> [ Endpoint ]
^ |
|------------------------- response unwinds back up --------------------------- +
// Mattrx Program.cs — order is deliberate, not decorative.
app.UseExceptionHandler(); // 1. wrap everything below
app.UseHttpsRedirection(); // 2.
app.UseRouting(); // 3. decide which endpoint matches
app.UseRateLimiter(); // 4. shed load before auth work
app.UseAuthentication(); // 5. who are you?
app.UseAuthorization(); // 6. are you allowed?
app.MapControllers(); // 7. run the endpoint
Senior signal: You reason about the pipeline as ordered and unwinding, and can predict what breaks when two components swap places.
2. Use vs Map vs Run — and what is short-circuiting?
Short answer: Use adds middleware that may call next; Run is terminal (never calls next); Map branches the pipeline on a path prefix. Short-circuiting is when middleware returns a response without calling next — e.g., a rate limiter returning 429.
Deep dive: Short-circuiting early is how you avoid wasting work on requests you'll reject.
// Short-circuit: reject unauthenticated health probes to an admin path without hitting the endpoint.
app.Use(async (ctx, next) =>
{
if (ctx.Request.Path.StartsWithSegments("/admin") && !ctx.User.Identity!.IsAuthenticated)
{
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
return; // did NOT call next -> pipeline short-circuits here
}
await next(ctx);
});
Senior signal: You know "don't call next = short-circuit" and put cheap rejections early to save downstream work.
3. Middleware vs action filters vs endpoint — when do you use each?
Short answer: Middleware is global and runs for every request (cross-cutting: logging, auth, exceptions). Filters run within MVC around actions and have access to model state and action context (validation, action-specific concerns). The endpoint is the handler itself.
Deep dive: Mattrx does request logging and tenant resolution in middleware (every request), but per-action authorization checks as filters/attributes.
// Middleware: applies to everything.
app.UseMiddleware<TenantResolutionMiddleware>();
// Filter/attribute: applies to specific actions, sees MVC context.
[Authorize(Policy = "reports:create")]
[HttpPost("reports")]
public Task<IActionResult> Create(...) { ... }
Senior signal: You place cross-cutting/global concerns in middleware and action-specific ones in filters, and know filters see MVC context that middleware doesn't.
4. Why must UseAuthentication/UseAuthorization sit between UseRouting and the endpoints?
Short answer: Authorization needs to know which endpoint matched (to read its [Authorize] metadata), which only exists after UseRouting; and it must run before the endpoint executes. Put them in the wrong order and endpoints run unauthorized — or authorization can't see endpoint policies.
Deep dive: This is the single most common pipeline bug. UseRouting selects the endpoint; UseAuthorization reads that endpoint's requirements; the endpoint then runs.
app.UseRouting(); // endpoint selected + its [Authorize] metadata attached
app.UseAuthentication(); // populate ctx.User
app.UseAuthorization(); // enforce the selected endpoint's policy
app.MapControllers(); // BUG if this ran before UseAuthorization
Senior signal: You explain why the order is fixed (routing produces endpoint metadata that authorization consumes), not just recite it.
5. Convention-based vs factory-based (IMiddleware) middleware — and injecting scoped services.
Short answer: Convention middleware is instantiated once (singleton-like), so you can't inject scoped services into its constructor — you must take them as parameters on InvokeAsync. IMiddleware (factory-based) is resolved per request from DI, so scoped injection works.
Deep dive: A convention middleware whose constructor takes a scoped DbContext captures it forever — a captive dependency bug.
// Convention: inject scoped services as InvokeAsync parameters (resolved per request), NOT ctor.
public sealed class TenantResolutionMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext ctx, ITenantStore tenants) // scoped, per-request
{
ctx.Items["tenant"] = await tenants.ResolveAsync(ctx.User);
await next(ctx);
}
}
Senior signal: You know convention middleware is effectively a singleton, so scoped deps go on InvokeAsync, or you switch to IMiddleware.
6. Centralized exception handling vs try/catch everywhere.
Short answer: Use UseExceptionHandler (or an IExceptionHandler in .NET 8+) to catch unhandled exceptions once, log them, and return a consistent ProblemDetails response — instead of scattering try/catch and leaking stack traces.
Deep dive: Mattrx maps domain exceptions to problem-details with the right status codes in one place; controllers stay clean.
// One handler for the whole app (.NET 8+ IExceptionHandler):
public sealed class ProblemDetailsHandler(IProblemDetailsService pds) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext ctx, Exception ex, CancellationToken ct)
{
ctx.Response.StatusCode = ex switch
{
NotFoundException => StatusCodes.Status404NotFound,
ValidationException => StatusCodes.Status400BadRequest,
_ => StatusCodes.Status500InternalServerError,
};
return await pds.TryWriteAsync(new() { HttpContext = ctx, /* ... */ });
}
}
Senior signal: You centralize error mapping, return ProblemDetails, and never leak stack traces to clients.
7. Minimal APIs vs Controllers — the senior trade-off.
Short answer: Minimal APIs are lighter and faster to write for small/focused endpoints; Controllers give you filters, model binding conventions, and structure that scale better for large apps. It's about surface area and team conventions, not "new vs old."
Deep dive: Mattrx uses minimal APIs for internal/health/webhook endpoints and controllers for the large tenant-facing API surface where filters and conventions pay off.
// Minimal API — great for a focused endpoint:
app.MapPost("/webhooks/stripe", async (StripeEvent e, IStripeWebhookHandler h, CancellationToken ct)
=> { await h.HandleAsync(e, ct); return Results.Ok(); });
Senior signal: You pick per surface area and team conventions, and know minimal APIs still support DI, filters (endpoint filters), and auth.
8. How do you stream a large response without buffering it in memory?
Short answer: Write directly to Response.Body (or return an IAsyncEnumerable/stream) instead of materializing a huge List or string — so a large export doesn't allocate the whole payload.
Deep dive: A Mattrx CSV export of millions of rows streams row-by-row; buffering it would blow the working set.
app.MapGet("/exports/events.csv", async (HttpContext ctx, IEventReader reader, CancellationToken ct) =>
{
ctx.Response.ContentType = "text/csv";
await using var writer = new StreamWriter(ctx.Response.Body);
await foreach (var row in reader.StreamAsync(ct)) // no buffering
await writer.WriteLineAsync(row.ToCsv());
});
Senior signal: You stream to Response.Body and use IAsyncEnumerable, framing it as memory/backpressure.
Block B — dependency injection & lifetimes
9. Singleton vs Scoped vs Transient — what does each mean for state and threading?
Short answer: Singleton = one instance for the app (must be thread-safe); Scoped = one per request (safe within a request, not across); Transient = a new instance every time it's resolved. The choice is about shared state and thread-safety.
Deep dive: Mattrx registers stateless helpers as singletons, per-request units of work (DbContext, tenant context) as scoped, and cheap stateless objects as transient.
builder.Services.AddSingleton<IClock, SystemClock>(); // stateless, shared, thread-safe
builder.Services.AddScoped<MattrxDbContext>(); // one per request
builder.Services.AddTransient<IReportBuilder, ReportBuilder>(); // fresh each resolve
Senior signal: You tie lifetime to state and thread-safety, not habit, and know a singleton must be thread-safe.
10. What is the captive dependency bug?
Short answer: A longer-lived service capturing a shorter-lived one — classically a singleton holding a scoped service. The scoped service now lives forever, leaking state across requests/tenants and breaking thread-safety.
Deep dive: ASP.NET Core's scope validation catches many of these at startup in Development.
// BUG: singleton CacheWarmer captures a scoped DbContext -> lives for the whole app.
builder.Services.AddSingleton<CacheWarmer>(); // ctor takes MattrxDbContext (scoped)
// FIX: create a scope per unit of work.
public sealed class CacheWarmer(IServiceScopeFactory scopes)
{
public async Task WarmAsync(CancellationToken ct)
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MattrxDbContext>();
// ...use db within this scope...
}
}
Senior signal: You name "captive dependency," reach for IServiceScopeFactory, and mention the scope validator.
11. How do you use a scoped service (like DbContext) inside a BackgroundService?
Short answer: A BackgroundService is a singleton, so you can't inject scoped services directly — inject IServiceScopeFactory and create a scope per unit of work.
Deep dive: Mattrx's ingestion worker creates a fresh scope per batch so each batch gets its own DbContext.
public sealed class IngestionWorker(IServiceScopeFactory scopes) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
using var scope = scopes.CreateScope(); // fresh scope per batch
var db = scope.ServiceProvider.GetRequiredService<MattrxDbContext>();
await ProcessBatchAsync(db, ct);
}
}
}
Senior signal: You create a scope per iteration/unit of work, not one for the worker's whole lifetime.
12. IOptions vs IOptionsSnapshot vs IOptionsMonitor?
Short answer: IOptions<T> is a singleton, computed once (no reload). IOptionsSnapshot<T> is scoped and recomputed per request (picks up changes, good for request-time config). IOptionsMonitor<T> is a singleton that supports live change notifications (good in singletons/background services).
Deep dive: Mattrx reads feature flags via IOptionsMonitor in a singleton so a config change takes effect without a restart.
public sealed class FeatureGate(IOptionsMonitor<FeatureFlags> flags) // singleton-safe, live reload
{
public bool IsEnabled(string name) => flags.CurrentValue.Enabled.Contains(name);
}
Senior signal: You match the options type to the consumer's lifetime and to whether you need live reload.
13. IHttpClientFactory and typed clients — what problem do they solve?
Short answer: They pool and rotate HttpMessageHandlers to avoid socket exhaustion (from new HttpClient() per call) and stale DNS (from one static client). Typed clients bind a configured client to a service.
Deep dive: Mattrx calls Stripe via a typed client with a resilience policy attached at registration.
builder.Services.AddHttpClient<StripeClient>(c => c.BaseAddress = new Uri("https://api.stripe.com"))
.AddStandardResilienceHandler(); // retries, circuit breaker, timeouts
public sealed class StripeClient(HttpClient http) { /* http is pooled + resilient */ }
Senior signal: You know both failure modes (socket exhaustion vs stale DNS) and reach for typed clients + resilience handlers.
14. How do you register and consume multiple implementations (or keyed services)?
Short answer: Register several implementations of an interface and inject IEnumerable<T> to get all of them; use keyed services (.NET 8+) to pick a specific one by key.
Deep dive: Mattrx dispatches a notification across channels by injecting all INotificationChannels; it selects a payment provider by key.
builder.Services.AddScoped<INotificationChannel, EmailChannel>();
builder.Services.AddScoped<INotificationChannel, PushChannel>();
// consume all:
public sealed class Notifier(IEnumerable<INotificationChannel> channels) { ... }
// keyed (.NET 8+): pick one by key
builder.Services.AddKeyedScoped<IPaymentProvider, StripeProvider>("stripe");
public sealed class Billing([FromKeyedServices("stripe")] IPaymentProvider provider) { ... }
Senior signal: You know IEnumerable<T> injection and keyed services, and use them instead of a hand-rolled factory switch.
15. Why is DbContext scoped, and what breaks if you make it a singleton?
Short answer: DbContext is not thread-safe and tracks entity state per unit of work. A singleton DbContext shared across concurrent requests corrupts its change tracker and throws or leaks data across tenants.
Deep dive: One request's tracked entities would bleed into another's — a multi-tenant data-integrity disaster.
// CORRECT: one DbContext per request (scoped), disposed at request end.
builder.Services.AddDbContext<MattrxDbContext>(o => o.UseSqlServer(cs)); // scoped by default
// A singleton DbContext + concurrent requests = "A second operation was started on this context" / cross-tenant leaks.
Senior signal: You cite "not thread-safe + per-unit-of-work change tracking" and connect a singleton DbContext to concurrency exceptions and tenant leakage.
Block C — hosting, config & performance
16. What is Kestrel, and how does the hosting model work?
Short answer: Kestrel is the cross-platform web server built into ASP.NET Core. In production it typically runs behind a reverse proxy (IIS, Nginx, Azure App Service front end) that handles TLS termination and load balancing; the generic host wires up DI, config, and logging.
Deep dive: Mattrx runs Kestrel on Azure App Service behind its front end; you configure forwarded headers so the app sees the real client IP/scheme.
// Trust the proxy's forwarded headers so ctx.Connection.RemoteIpAddress / scheme are correct.
builder.Services.Configure<ForwardedHeadersOptions>(o =>
o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto);
app.UseForwardedHeaders();
Senior signal: You mention reverse proxy + TLS termination + UseForwardedHeaders, not just "Kestrel is the server."
17. How does configuration work — providers, precedence, and secrets?
Short answer: IConfiguration layers multiple providers (appsettings.json, environment-specific json, environment variables, command line, Key Vault, user-secrets in dev) where later providers override earlier ones. Secrets never go in appsettings — they come from Key Vault / env vars.
Deep dive: Mattrx reads the Azure SQL and Redis connection strings from Key Vault via the configuration provider, so nothing sensitive is in source.
builder.Configuration.AddAzureKeyVault(vaultUri, credential); // highest-priority secrets
var cs = builder.Configuration.GetConnectionString("AzureSql"); // resolved from Key Vault
Senior signal: You know the override order and that secrets belong in Key Vault/env vars/user-secrets, never appsettings.
18. BackgroundService/IHostedService — how do you shut them down gracefully?
Short answer: ExecuteAsync receives a stoppingToken that's signalled on shutdown; honor it, and finish in-flight work within the shutdown timeout so you don't drop messages mid-process.
Deep dive: Mattrx's Kafka consumer stops pulling on the token, commits its offset, and exits cleanly so no batch is half-processed on a deploy.
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var batch = consumer.Consume(stoppingToken);
await ProcessAsync(batch, stoppingToken);
consumer.Commit(batch); // only after successful processing
}
// graceful: loop exits, offsets committed, no half-done work
}
Senior signal: You honor the stopping token and reason about what happens on deploy (graceful drain, no lost/duplicated work).
19. What is thread-pool starvation, and how does sync-over-async cause it?
Short answer: Blocking a thread-pool thread (.Result/.Wait()) on async I/O ties up threads that can't serve other requests; under load the pool can't grow fast enough and latency explodes. The cure is async all the way.
Deep dive: One .Result on a hot Mattrx path dragged p95 up under load because request threads sat blocked instead of returning to the pool.
// STARVATION: blocks a pool thread on I/O.
var kpis = _service.GetKpisAsync(t, c, r, ct).Result;
// CORRECT: keep the thread free.
var kpis = await _service.GetKpisAsync(t, c, r, ct);
Senior signal: You connect sync-over-async to pool starvation under load, not just "it's slower."
20. Output caching vs response caching vs IMemoryCache vs distributed cache?
Short answer: IMemoryCache is in-process (fast, per-instance, lost on restart, not shared); a distributed cache (Redis) is shared across instances. Response/output caching cache whole HTTP responses; output caching (.NET 7+) is the newer, server-controlled option.
Deep dive: Mattrx uses Redis (IDistributedCache) for KPI results shared across instances, and output caching for a few public, cacheable GETs.
builder.Services.AddOutputCache();
app.MapGet("/public/pricing", () => GetPricing())
.CacheOutput(p => p.Expire(TimeSpan.FromMinutes(10))); // server-side, shared per instance policy
Senior signal: You distinguish in-process vs distributed and know a multi-instance app needs a shared cache for correctness.
21. Health checks — liveness vs readiness, and why the difference matters?
Short answer: Liveness = "is the process alive?" (restart if not). Readiness = "can it serve traffic right now?" (dependencies up, warmed). Orchestrators (k8s, Azure Container Apps) use them differently — failing readiness pulls you from the load balancer without killing you.
Deep dive: Mattrx's readiness check verifies Azure SQL + Redis; liveness is a cheap "the host responds."
builder.Services.AddHealthChecks()
.AddSqlServer(cs, tags: ["ready"])
.AddRedis(redisCs, tags: ["ready"]);
app.MapHealthChecks("/health/live", new() { Predicate = _ => false }); // just alive
app.MapHealthChecks("/health/ready", new() { Predicate = h => h.Tags.Contains("ready") });
Senior signal: You separate liveness from readiness and know readiness gates the load balancer while liveness triggers restarts.
22. How does the built-in rate limiter (.NET 7+) work?
Short answer: AddRateLimiter provides fixed-window, sliding-window, token-bucket, and concurrency limiters as middleware, with partitioning (e.g., per tenant) and a rejection response.
Deep dive: Mattrx partitions a token-bucket limiter by tenant so one tenant's burst can't starve others (the same isolation as its gateway limiter).
builder.Services.AddRateLimiter(o =>
{
o.AddPolicy("per-tenant", ctx => RateLimitPartition.GetTokenBucketLimiter(
ctx.User.FindFirstValue("tenant_id") ?? "anon",
_ => new TokenBucketRateLimiterOptions { TokenLimit = 200, TokensPerPeriod = 100, ReplenishmentPeriod = TimeSpan.FromSeconds(1) }));
o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});
app.UseRateLimiter();
Senior signal: You partition per tenant/client and place the limiter early to shed load before expensive work.
23. How do model binding and validation work, and how do you prevent over-posting?
Short answer: Model binding maps request data to parameters; [ApiController] auto-returns 400 on invalid model state. Over-posting is when a client sends fields you didn't intend to accept (e.g., IsAdmin) — prevent it by binding to a purpose-built request DTO, never your entity.
Deep dive: Mattrx binds to explicit request records, never EF entities, so a client can't set fields it shouldn't.
// SAFE: bind to a DTO with only the fields the client may set.
public sealed record CreateCampaignRequest(string Name, decimal Budget); // no TenantId, no Id
[HttpPost] public Task<IActionResult> Create([FromBody] CreateCampaignRequest req) { ... }
// Never: public Task Create(Campaign entity) // over-posting: client could set TenantId/Id
Senior signal: You bind to request DTOs (not entities), rely on [ApiController] validation, and name over-posting as the risk.
Block D — auth, security & APIs
24. Authentication vs Authorization — and the middleware order that trips people up.
Short answer: Authentication establishes who you are (populates ctx.User); authorization decides what you can do. UseAuthentication must run before UseAuthorization, and both after UseRouting.
Deep dive: If authorization runs before authentication, ctx.User is anonymous and every [Authorize] fails (or, misconfigured, passes).
app.UseRouting();
app.UseAuthentication(); // sets ctx.User from the bearer token
app.UseAuthorization(); // evaluates policies against ctx.User
Senior signal: You state the order and the reason (authz reads the identity authn produced, for the endpoint routing selected).
25. How is a JWT bearer token validated?
Short answer: The framework verifies the signature (against the issuer's public keys / JWKS), the issuer, the audience, and expiry — every request, statelessly. A token that fails any check is rejected.
Deep dive: Mattrx validates Entra ID tokens; the audience check is what stops a token minted for another API being replayed against Mattrx.
builder.Services.AddAuthentication().AddJwtBearer(o =>
{
o.Authority = "https://login.microsoftonline.com/{tenant}/v2.0"; // JWKS discovered here
o.TokenValidationParameters = new()
{
ValidateIssuer = true, ValidateAudience = true,
ValidAudience = "api://mattrx", ValidateLifetime = true, // signature validated via Authority
};
});
Senior signal: You name all four checks (sig/JWKS, issuer, audience, expiry) and call out audience-binding as the confused-deputy guard.
26. Authorization: roles vs claims vs policies vs resource-based.
Short answer: Roles are coarse claims; claims are key/value facts on the identity; policies are named, composable rules over claims (the recommended approach); resource-based authorization checks permission against a specific resource instance (does this user own this campaign?).
Deep dive: Mattrx uses policies for scopes and resource-based auth for per-record ownership.
builder.Services.AddAuthorization(o =>
o.AddPolicy("reports:create", p => p.RequireClaim("scope", "reports:create")));
// resource-based: can THIS user act on THIS campaign?
var result = await _authz.AuthorizeAsync(User, campaign, "edit");
if (!result.Succeeded) return Forbid();
Senior signal: You prefer policies over sprinkled role checks and know resource-based auth for instance-level ownership.
27. How do you enforce multi-tenant isolation correctly?
Short answer: Derive the tenant from the authenticated token, never from a query string, route, or header the client controls — then scope every query by it (ideally with row-level security as a backstop).
Deep dive: Taking tenantId from the request lets a caller read another tenant's data by changing a parameter. Mattrx binds tenant from the token claim and filters all queries by it.
// SAFE: tenant from the verified token, not from input.
var tenantId = User.FindFirstValue("tenant_id")!; // trusted
var data = await _db.Campaigns.Where(c => c.TenantId == tenantId).ToListAsync(ct);
// NEVER: var tenantId = Request.Query["tenantId"]; // client-controlled -> cross-tenant read
Senior signal: You say "tenant from the token, never from client input" and mention RLS as defense-in-depth.
28. How does CORS work, and what's the common misconfiguration?
Short answer: CORS is a browser mechanism: for cross-origin requests the browser sends a preflight OPTIONS and the server must return Access-Control-Allow-* headers permitting the origin. The classic mistake is AllowAnyOrigin() combined with credentials (disallowed, and insecure).
Deep dive: Mattrx allows only its known SPA origins and enables credentials explicitly.
builder.Services.AddCors(o => o.AddPolicy("spa", p => p
.WithOrigins("https://app.mattrx.co") // explicit origins, not AllowAnyOrigin
.AllowCredentials()
.AllowAnyHeader().AllowAnyMethod()));
app.UseCors("spa");
Senior signal: You know CORS is browser-enforced (not security on its own) and never pair AllowAnyOrigin with credentials.
29. Antiforgery/CSRF — when do you need it?
Short answer: CSRF protection matters when the browser auto-sends credentials — i.e., cookie-based auth. Pure bearer-token APIs (token in an Authorization header the browser doesn't attach automatically) aren't CSRF-vulnerable in the same way, so they typically don't need antiforgery tokens.
Deep dive: Mattrx's SPA uses bearer tokens, so it relies on token auth + CORS rather than antiforgery; a cookie-auth server-rendered app would need [ValidateAntiForgeryToken].
// Cookie-auth form posts need antiforgery; bearer-token APIs generally don't.
[ValidateAntiForgeryToken] // only meaningful for cookie-based flows
public IActionResult UpdateProfile(ProfileForm form) { ... }
Senior signal: You tie CSRF to ambient credentials (cookies) and explain why bearer-token APIs differ.
30. Where should cross-cutting concerns live — middleware or a MediatR pipeline behavior?
Short answer: HTTP-level concerns (auth, exceptions, rate limiting, forwarded headers) belong in middleware; application-level concerns that should apply to every command/query regardless of transport (validation, logging, transactions, retries) belong in MediatR pipeline behaviors.
Deep dive: Mattrx runs validation and a Unit-of-Work transaction as MediatR behaviors so they apply whether a request came via HTTP, a queue, or a test.
// Behavior wraps every handler — transport-agnostic.
public sealed class ValidationBehavior<TReq, TRes>(IEnumerable<IValidator<TReq>> validators)
: IPipelineBehavior<TReq, TRes> where TReq : notnull
{
public async Task<TRes> Handle(TReq req, RequestHandlerDelegate<TRes> next, CancellationToken ct)
{
foreach (var v in validators) await v.ValidateAndThrowAsync(req, ct);
return await next();
}
}
Senior signal: You split HTTP concerns (middleware) from application concerns (behaviors) and justify it by "applies regardless of transport."
Bonus — what makes an answer "senior" in ASP.NET Core?
Short answer: A junior describes a feature; a senior explains the ordering, lifetime, and failure mode. "What is middleware" gets "a request delegate chain" from a junior and "an ordered, unwinding pipeline where auth must sit between routing and endpoints, and a mis-order silently lets requests through" from a senior.
Deep dive: The recurring senior lens across all 30: order (pipeline), lifetime (DI/captive dependency), thread-safety (singletons, DbContext), and trust boundary (tenant/auth from the token). Name the mechanism, the production failure it prevents, and the trade-off.
Senior signal: You volunteer the failure mode before being asked, and you can say "here's the wrong order / lifetime and exactly what it breaks."
The model to carry forward
Senior ASP.NET Core is four instincts: the pipeline is ordered and it unwinds; lifetimes are about shared state and thread-safety; the tenant and the user come from the token, never the request; and cross-cutting concerns live at the right layer. Answer every question with the mechanism, the real failure it prevents, and the trade-off — the signal that you've operated this in production, not just scaffolded it.
Further reading
- React Interview Questions for Senior Developers — Hooks, Reconciliation, Fiber & Performance (Deep Answers)
- C# Interview Questions for Senior Developers — async/await, GC & Memory, the Type System & LINQ (Deep Answers)
- Scaling ASP.NET Core APIs to 100,000 Requests per Minute
Prepping for a senior .NET interview and want these drilled live, or a mock focused on your weak block? I'm always happy to help — reach me at randhir.jassal@gmail.com.
Get the next issue
A short, curated email with the newest posts and questions.