ASP.NET Core interview questions and answers
ASP.NET Core interview questions from the basics (Program.cs, middleware, dependency injection, routing) to running real APIs in production. Each answer gives the reasoning interviewers look for, with a short code example where it helps.
Mixed · 45 questions · Tap a question to see the answer.
New to this? Learn it step by step in the free ASP.NET Core MVC course.
Q1. Why does the order of middleware matter? Give an example of a wrong order.
Middleware runs in the order it is added for the request, and in reverse for the response. Each component decides whether to call the next one.
A common bug is calling
UseAuthorization()beforeUseAuthentication()(or beforeUseRouting()when you call it explicitly): authorization then runs without a signed-in user and every protected endpoint returns 401. Exception handling should be first so it can catch errors from everything after it.app.UseExceptionHandler("/error"); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers();Q2. When would you choose minimal APIs over controllers?
Minimal APIs suit small services and microservices: less ceremony, fast startup, and they support Native AOT. Endpoint filters, route groups and
TypedResultscover validation, shared configuration and OpenAPI.Controllers still fit large APIs that benefit from conventions, model-binding attributes and action filters, or teams already organised around them. Both run on the same routing and can live in one app.
var orders = app.MapGroup("/orders").RequireAuthorization(); orders.MapGet("/{id:int}", async Task<Results<Ok<Order>, NotFound>> (int id, AppDbContext db) => await db.Orders.FindAsync(id) is { } o ? TypedResults.Ok(o) : TypedResults.NotFound());Q3. How do you read typed configuration, and what is the difference between
IOptions,IOptionsSnapshotandIOptionsMonitor?Bind a section to a class with
services.Configure<T>(config.GetSection("..."))(orAddOptions<T>().BindConfiguration(...), which also lets you add validation).IOptions<T>is read once and never changes.IOptionsSnapshot<T>is scoped and re-reads per request, so it picks up reloaded config.IOptionsMonitor<T>is a singleton that always returns the current value and raisesOnChange, so it is the one to use inside singletons.builder.Services.AddOptions<SmtpOptions>() .BindConfiguration("Smtp") .ValidateDataAnnotations() .ValidateOnStart();Q4. Walk through how JWT bearer authentication works in an ASP.NET Core API.
The client signs in with an identity provider (for example Microsoft Entra ID) and receives a signed access token. It sends the token in the
Authorization: Bearer <token>header.AddAuthentication().AddJwtBearer()validates the signature with the provider's published keys, then checks issuer, audience and expiry. The claims becomeHttpContext.User, and[Authorize]or policies decide access. Keep tokens short-lived, and never put secrets in a JWT, because its payload is only encoded, not encrypted.Q5. How do you return consistent error responses for unhandled exceptions in an API?
Register
AddProblemDetails()and useUseExceptionHandler(). Unhandled exceptions then become RFC 7807 Problem Details JSON with the right status code, and no stack trace leaks in production.For known exceptions, implement
IExceptionHandler(ASP.NET Core 8+) to map, say, aNotFoundExceptionto 404. Log the exception once there instead of try/catch in every action.builder.Services.AddProblemDetails(); builder.Services.AddExceptionHandler<NotFoundHandler>(); ... app.UseExceptionHandler();Q6. Compare in-memory caching, distributed caching and output caching.
IMemoryCachestores objects in the process: fastest, but each server has its own copy and it is lost on restart. Distributed caching (IDistributedCache, typically Redis) is shared by all instances and survives restarts, at the cost of a network hop and serialization.Output caching caches whole HTTP responses for endpoints, with policies and tag-based invalidation.
HybridCache(.NET 9+) combines a local and a distributed layer and protects against cache stampedes.Q7. How would you protect a public API from too many requests?
Use the built-in rate limiting middleware:
AddRateLimiterwith a fixed window, sliding window, token bucket or concurrency limiter, partitioned by user, API key or IP address, and return 429 when the limit is hit.In a multi-instance deployment the built-in limiter is per instance, so add a gateway-level limit as well (Azure API Management or Front Door) for a global limit.
builder.Services.AddRateLimiter(o => o.AddFixedWindowLimiter("api", l => { l.PermitLimit = 100; l.Window = TimeSpan.FromMinutes(1); })); ... app.UseRateLimiter(); app.MapGet("/items", GetItems).RequireRateLimiting("api");Q8. How do you run background work in ASP.NET Core, and what are the risks?
Implement
BackgroundServiceand register it withAddHostedService. Use aChannel<T>as an in-process queue when requests need to hand off work.Risks: in-process work is lost if the app restarts or scales in, and hosted services are singletons, so they must create a scope to use scoped services such as a
DbContext. For work that must not be lost, use a durable queue (Azure Service Bus, Storage Queues) and a separate worker or Azure Functions.Q9. What are health checks used for, and what is the difference between liveness and readiness?
AddHealthChecks()exposes endpoints that orchestrators and load balancers poll. Liveness answers 'is the process alive?': if it fails, restart it. Readiness answers 'can it serve traffic now?': if it fails, stop sending requests but don't restart.Put dependency checks (database, Redis) on the readiness endpoint only; otherwise a database outage makes the platform restart every healthy instance.
builder.Services.AddHealthChecks() .AddCheck("self", () => HealthCheckResult.Healthy()) .AddSqlServer(connStr, tags: ["ready"]); app.MapHealthChecks("/health/live", new() { Predicate = c => c.Name == "self" }); app.MapHealthChecks("/health/ready", new() { Predicate = c => c.Tags.Contains("ready") });Q10. A browser app on another domain gets a CORS error calling your API, but Postman works. Why?
CORS is enforced by browsers, not servers. Postman ignores it. The browser blocks the response unless the API returns
Access-Control-Allow-Originfor that origin, and for non-simple requests it first sends an OPTIONS preflight.Configure a named policy with the exact allowed origins, methods and headers, and call
UseCorsbefore authorization. Don't combineAllowAnyOriginwithAllowCredentials; it is unsafe and the framework rejects it.builder.Services.AddCors(o => o.AddPolicy("web", p => p .WithOrigins("https://app.example.com") .AllowAnyHeader() .AllowAnyMethod())); ... app.UseCors("web");Q11. An API endpoint that lists 50 orders runs 51 SQL queries. What is happening and how do you fix it?
This is the N+1 problem: one query for the orders, then one query per order when a navigation property (such as
Customer) is loaded lazily inside a loop or during serialization.Load what you need in one round trip: project with
Selectinto a DTO (best, since it fetches only the needed columns), or useInclude. UseAsNoTracking()for read-only queries and check the SQL with logging.var list = await db.Orders .AsNoTracking() .Select(o => new OrderDto(o.Id, o.Total, o.Customer.Name)) .ToListAsync(ct);Q12. Where should connection strings and API keys live for local development and for production?
Locally, use User Secrets (
dotnet user-secrets), which keeps them outside the repository. Never commit them toappsettings.json.In Azure, prefer managed identity so there is no secret at all (for Azure SQL, Storage, Key Vault). For the secrets that remain, store them in Azure Key Vault and load them with the Key Vault configuration provider, or reference them from App Service settings.
Q13. What is ASP.NET Core, and how is it different from the old ASP.NET?
ASP.NET Core is Microsoft's open-source, cross-platform framework for web apps and APIs on modern .NET. It runs on Windows, Linux and macOS, is hosted by its own fast web server (Kestrel), and has dependency injection, configuration and logging built in.
The old ASP.NET runs only on .NET Framework and Windows with IIS. ASP.NET Core was rewritten around a small middleware pipeline, so apps include only what they use, run in containers, and are much faster.
Q14. What happens in Program.cs of an ASP.NET Core app?
WebApplication.CreateBuildersets up configuration, logging and the dependency injection container. You register services onbuilder.Services, thenbuilder.Build()creates the app.After that you add middleware in order (HTTPS redirection, static files, routing, authentication, authorization), map endpoints such as controllers or minimal APIs, and call
app.Run()to start Kestrel.var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();Q15. What is Kestrel, and do you still need IIS or a reverse proxy?
Kestrel is the cross-platform web server built into ASP.NET Core. It is fast and can face the internet directly.
Many teams still put a reverse proxy in front of it, such as IIS on Windows, Nginx on Linux or a cloud load balancer, to handle TLS certificates, load balancing, and serving several apps on one port. On IIS, the ASP.NET Core Module hosts the app in-process for the best performance.
Q16. How does dependency injection work in ASP.NET Core?
You register services with an interface and a lifetime in
builder.Services, and ASP.NET Core creates them and passes them into constructors of controllers, middleware and other services. Classes depend on interfaces, not on concrete classes, which makes them easy to test and change.Lifetimes: Transient creates a new object every time, Scoped creates one per HTTP request, and Singleton creates one for the whole app.
builder.Services.AddScoped<IOrderService, OrderService>(); public class OrdersController(IOrderService orders) : ControllerBase { [HttpGet("{id}")] public async Task<IActionResult> Get(int id) => Ok(await orders.FindAsync(id)); }Q17. How do you write custom middleware, and when would you?
Middleware is a component in the request pipeline that can run code before and after the next component. Write it as a class with an
InvokeAsync(HttpContext context)method that calls_next(context), and add it withapp.UseMiddleware<T>().Use it for cross-cutting concerns that apply to many requests: adding a correlation ID, timing requests, or custom headers. For logic that belongs to one endpoint, use a filter or put it in the endpoint instead.
public class TimingMiddleware(RequestDelegate next, ILogger<TimingMiddleware> log) { public async Task InvokeAsync(HttpContext ctx) { var sw = Stopwatch.StartNew(); await next(ctx); log.LogInformation("{Path} took {Ms} ms", ctx.Request.Path, sw.ElapsedMilliseconds); } } app.UseMiddleware<TimingMiddleware>();Q18. What are filters in ASP.NET Core MVC, and how do they differ from middleware?
Filters run inside the MVC action pipeline, around a controller action. There are authorization, resource, action, exception and result filters. Because they run after routing, they know which controller and action was chosen, and can read model state and action arguments.
Middleware runs for every request, including static files, and knows nothing about controllers. Use filters for MVC-specific concerns such as validating a model or checking a permission on certain actions.
Q19. How do model binding and validation work in ASP.NET Core?
Model binding fills action parameters from the route, query string, form or JSON body. Data annotations such as
[Required]and[Range]on the model describe the rules, and the results go intoModelState.With
[ApiController], an invalid model automatically returns a 400 Bad Request with the errors, so you do not need to checkModelState.IsValidyourself. In MVC views, you check it and show the form again with the error messages.public record CreateProduct( [Required, StringLength(100)] string Name, [Range(1, 100000)] decimal Price); [HttpPost] public IActionResult Create(CreateProduct input) => Ok(); // 400 if invalidQ20. What is the difference between conventional routing and attribute routing?
Conventional routing uses a pattern defined once, such as
{controller=Home}/{action=Index}/{id?}, and is common for MVC sites with views. Attribute routing puts the route on the controller or action, such as[Route("api/orders")]and[HttpGet("{id:int}")], and is the usual choice for APIs.Route constraints such as
:intmake a route match only valid values, so/api/orders/abcreturns 404 instead of reaching the action.Q21. What is the difference between returning IActionResult, ActionResult<T> and a plain object from an API action?
Returning a plain object always produces 200 OK with that object as JSON.
IActionResultlets you return different responses such asNotFound()orBadRequest(), but loses the type for API documentation.ActionResult<T>gives both: you can returnTfor 200 OK or any other result, and tools like OpenAPI know the success type.[HttpGet("{id}")] public async Task<ActionResult<OrderDto>> Get(int id) { var order = await orders.FindAsync(id); return order is null ? NotFound() : order; }Q24. How do configuration and environments (Development, Staging, Production) work?
Configuration is read from several sources in order: appsettings.json, then appsettings.{Environment}.json, user secrets in development, environment variables and command-line arguments. Later sources override earlier ones.
The environment comes from the
ASPNETCORE_ENVIRONMENTvariable. Code can checkapp.Environment.IsDevelopment(), for example to show the detailed error page only during development.Q25. How does logging work in ASP.NET Core, and what is structured logging?
You inject
ILogger<T>and write messages at levels such as Information, Warning and Error. Providers send them to the console, files, Application Insights or other systems, and the minimum level is set in configuration per category.Structured logging uses message templates with named placeholders, such as
"Order {OrderId} failed", instead of string concatenation. The values are stored as fields, so you can search and filter logs byOrderId.logger.LogWarning("Payment {PaymentId} failed for order {OrderId}", paymentId, orderId);Q26. Why should you use IHttpClientFactory to call other APIs?
Creating a new
HttpClientper call can run out of sockets, and a single static client can miss DNS changes.IHttpClientFactorymanages the underlying handlers for you and fixes both problems.Typed clients also keep base addresses and headers in one place, and can add resilience such as retries and timeouts.
builder.Services.AddHttpClient<WeatherClient>(c => c.BaseAddress = new Uri("https://api.example.com/")); public class WeatherClient(HttpClient http) { public Task<Forecast?> GetAsync(string city) => http.GetFromJsonAsync<Forecast>($"forecast/{city}"); }Q27. Why should controller actions be async when they call a database or another API?
While an async action awaits I/O, its thread goes back to the thread pool and can serve other requests. Blocking calls hold a thread doing nothing, so under load the pool runs out and requests queue up.
Use async all the way down (for example
ToListAsyncwith EF Core) and never block with.Resultor.Wait(). Pass the request'sCancellationTokenso work stops when the client goes away.Q28. How would you version a public Web API?
Common choices are a version in the URL (
/api/v2/orders), a query string (?api-version=2.0) or a header. URL versions are the easiest for clients to see and test.Keep old versions running while clients move, mark them deprecated in responses and documentation, and only remove them after a published date. Avoid breaking changes inside a version: adding fields is safe, renaming or removing them is not.
Q29. How do you document an ASP.NET Core API with OpenAPI?
Since .NET 9, ASP.NET Core can generate an OpenAPI document itself with
builder.Services.AddOpenApi()andapp.MapOpenApi(). Tools such as Swagger UI or Scalar can show that document as an interactive page, and client code can be generated from it.Use
ActionResult<T>,[ProducesResponseType]and XML comments so the document shows the real response types and descriptions.Q30. How do you write integration tests for an ASP.NET Core API?
Use
WebApplicationFactory<Program>from the Microsoft.AspNetCore.Mvc.Testing package. It starts the real app in memory and gives you anHttpClient, so tests go through routing, middleware, model binding and serialization.Override services for the test, for example to use a test database or a fake email sender, with
WithWebHostBuilderandConfigureTestServices.public class OrdersApiTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>> { [Fact] public async Task Get_unknown_order_returns_404() { var client = factory.CreateClient(); var res = await client.GetAsync("/api/orders/999999"); Assert.Equal(HttpStatusCode.NotFound, res.StatusCode); } }Q31. What are the Blazor render modes, and how do you choose one?
Static server rendering (static SSR) renders HTML on the server with no interactivity; it is the fastest and best for content pages.
Interactive Server runs components on the server and sends UI updates over a SignalR connection: quick to start, full .NET on the server, but every user holds a connection and latency matters.
Interactive WebAssembly downloads the .NET runtime and runs components in the browser: works offline after loading, no server connection, but a larger first download. Interactive Auto starts with Server and switches to WebAssembly once it has downloaded.
You can set the render mode per component or per page, so a typical app is mostly static SSR with interactivity only where it is needed.
@page "/counter" @rendermode InteractiveServer <button @onclick="() => count++">Clicked @count times</button> @code { int count; }Q32. What is SignalR, and when would you use it instead of polling an API?
SignalR adds real-time, two-way communication between server and clients. It uses WebSockets when available and falls back to Server-Sent Events or long polling.
Use it when the server must push updates as they happen: chat, notifications, live dashboards, progress of long jobs. Polling wastes requests and delays updates.
When you run more than one server instance, you need a backplane such as Redis or Azure SignalR Service so a message reaches clients connected to any server.
public class NotificationsHub : Hub { public Task Join(string group) => Groups.AddToGroupAsync(Context.ConnectionId, group); } // elsewhere, via IHubContext<NotificationsHub> await hub.Clients.Group("admins").SendAsync("orderPlaced", orderId);Q33. When would you choose gRPC over a REST API?
gRPC uses HTTP/2 and Protocol Buffers: a strict contract in a .proto file, compact binary messages, generated clients and built-in streaming. It suits fast service-to-service calls inside your system.
REST with JSON is easier for public APIs, browsers and third parties: human-readable, works with any HTTP client and with caching and gateways.
A common design is gRPC between internal microservices and REST or GraphQL at the edge. Browsers cannot call gRPC directly without gRPC-Web.
Q35. Why do APIs use short-lived access tokens with refresh tokens?
A JWT access token cannot easily be revoked before it expires, so it should live only a few minutes. If it leaks, the damage window is small.
A refresh token is long-lived, stored securely by the client, and used only with the identity provider to get a new access token. It can be revoked, rotated on each use, and bound to a client, so you get short-lived access without making users sign in again.
Do not invent your own token server; use an identity provider such as Microsoft Entra ID or a proven library.
Q36. What is CSRF, and how does ASP.NET Core protect against it?
Cross-site request forgery tricks a signed-in user's browser into sending a request to your site from another site, and the browser attaches your cookies automatically.
ASP.NET Core issues an antiforgery token in a hidden form field and validates it on POST, so a forged request from another site does not have it. MVC and Razor Pages forms do this automatically, and Blazor forms include it too.
APIs that authenticate with bearer tokens in a header are not vulnerable in the same way, because browsers do not add those headers automatically. Setting cookies to SameSite=Lax or Strict adds another layer.
Q37. What do UseHttpsRedirection and UseHsts do?
UseHttpsRedirectionredirects HTTP requests to HTTPS.UseHstssends the Strict-Transport-Security header, which tells browsers to use only HTTPS for your domain for a period of time, even if the user types http://.HSTS is normally enabled only outside Development, because a browser remembers it and it is hard to undo for localhost. Behind a load balancer or reverse proxy that ends TLS, configure forwarded headers so the app knows the original request was HTTPS.
if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/error"); app.UseHsts(); } app.UseHttpsRedirection();Q38. What are endpoint filters in minimal APIs?
Endpoint filters run code before and after a minimal API handler, similar to action filters in MVC. They receive the arguments, can validate them, short-circuit with a result, or change the response.
They are good for cross-cutting work on a group of endpoints, such as validation or logging, without writing middleware that runs for every request.
app.MapPost("/orders", (CreateOrder cmd) => Results.Created($"/orders/1", cmd)) .AddEndpointFilter(async (ctx, next) => { var cmd = ctx.GetArgument<CreateOrder>(0); if (cmd.Quantity <= 0) return Results.ValidationProblem(new Dictionary<string, string[]> { ["Quantity"] = ["Must be positive"] }); return await next(ctx); });Q39. What is the difference between Results and TypedResults in minimal APIs?
Results.Ok(x)returnsIResult, so the framework cannot see from the method signature which responses are possible.TypedResults.Ok(x)returns a concrete type such asOk<T>.With typed results and a union return type such as
Results<Ok<Product>, NotFound>, OpenAPI documentation describes each response automatically, and unit tests can check the result type without running HTTP.app.MapGet("/products/{id}", async Task<Results<Ok<Product>, NotFound>> (int id, AppDb db) => await db.Products.FindAsync(id) is { } p ? TypedResults.Ok(p) : TypedResults.NotFound());Q40. How do you handle file uploads safely in ASP.NET Core?
For small files, bind
IFormFile. For large files, stream the request body instead of buffering it, and raise the request size limit only on that endpoint.Never trust the file name or content type from the client: generate your own file name, check the extension and the file's signature, enforce a size limit, and scan for malware if the files are shared.
Store files outside the web root, ideally in blob storage, and serve them through a controlled endpoint or a short-lived SAS link.
[HttpPost, RequestSizeLimit(10_000_000)] public async Task<IActionResult> Upload(IFormFile file) { var name = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}"; await using var stream = System.IO.File.Create(Path.Combine(_uploadDir, name)); await file.CopyToAsync(stream); return Ok(new { name }); }Q41. How would you add paging to an API that returns a large list?
Never return an unbounded list. Accept page parameters with a sensible default and a maximum page size, and return the items plus paging information such as a total count or a link to the next page.
Offset paging (
Skip/Take) is simple but gets slower on deep pages and can skip or repeat rows when data changes. Keyset (cursor) paging,WHERE Id > lastId ORDER BY Id, stays fast and stable for large or changing data, so it suits infinite scroll and exports.Always order by a unique key, otherwise pages are not deterministic.
app.MapGet("/orders", async (AppDb db, int afterId = 0, int pageSize = 50) => { pageSize = Math.Clamp(pageSize, 1, 200); var items = await db.Orders.Where(o => o.Id > afterId) .OrderBy(o => o.Id).Take(pageSize).ToListAsync(); return new { items, nextAfterId = items.LastOrDefault()?.Id }; });Q42. A client retries a POST that creates a payment, and the customer is charged twice. How do you prevent this?
Make the operation idempotent. The client sends a unique Idempotency-Key header with the request. The server stores the key with the result of the first request, and if the same key arrives again it returns the stored result instead of charging again.
Back it with a unique constraint in the database so two requests racing at the same time cannot both succeed. GET, PUT and DELETE should already be idempotent by design; POST needs this extra step.
Q43. What is Native AOT for ASP.NET Core, and what are its limits?
Native AOT compiles the app ahead of time into a single native executable with no JIT. It starts much faster and uses less memory, which suits containers, serverless and small APIs.
The limits come from trimming and no runtime code generation: reflection-heavy libraries, runtime-generated serializers and some features do not work. Minimal APIs with source-generated System.Text.Json are supported, while MVC, Razor Pages and Blazor Server are not supported with Native AOT. The
webapiaottemplate sets this up.Q44. An API endpoint is slow in production. How do you find out why?
Start from data, not guesses. Look at traces in Application Insights or another OpenTelemetry backend to see where the time goes: database calls, outgoing HTTP calls or the app itself.
Check the usual suspects: N+1 database queries, missing indexes, blocking calls such as
.Result, thread-pool starvation, large responses and missing caching.Use
dotnet-countersto watch request rate, thread-pool queue length, GC and exceptions live, anddotnet-traceor a memory dump for deeper analysis. Fix one thing, measure again, and add a test or alert so it does not come back.Q45. What is ProblemDetails, and how do you return it from an ASP.NET Core API?
ProblemDetails is a standard JSON error format (RFC 9457) with fields such as type, title, status, detail and instance. Using it gives clients one predictable error shape.
builder.Services.AddProblemDetails()makes the framework produce it for errors and status codes,app.UseExceptionHandler()turns unhandled exceptions into it, and validation failures becomeValidationProblemDetailswith the field errors. Never put stack traces in it outside Development.builder.Services.AddProblemDetails(); var app = builder.Build(); app.UseExceptionHandler(); app.UseStatusCodePages();
Original questions written to explain concepts; not taken from any certification exam. Spotted a mistake? See our corrections policy.