ASP.NET Core

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.

  1. 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() before UseAuthentication() (or before UseRouting() 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();

    Official documentation

  2. 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 TypedResults cover 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());

    Official documentation

  3. Q3. How do you read typed configuration, and what is the difference between IOptions, IOptionsSnapshot and IOptionsMonitor?

    Bind a section to a class with services.Configure<T>(config.GetSection("...")) (or AddOptions<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 raises OnChange, so it is the one to use inside singletons.

    builder.Services.AddOptions<SmtpOptions>()
        .BindConfiguration("Smtp")
        .ValidateDataAnnotations()
        .ValidateOnStart();

    Official documentation

  4. 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 become HttpContext.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.

    Official documentation

  5. Q5. How do you return consistent error responses for unhandled exceptions in an API?

    Register AddProblemDetails() and use UseExceptionHandler(). 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, a NotFoundException to 404. Log the exception once there instead of try/catch in every action.

    builder.Services.AddProblemDetails();
    builder.Services.AddExceptionHandler<NotFoundHandler>();
    ...
    app.UseExceptionHandler();

    Official documentation

  6. Q6. Compare in-memory caching, distributed caching and output caching.

    IMemoryCache stores 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.

    Official documentation

  7. Q7. How would you protect a public API from too many requests?

    Use the built-in rate limiting middleware: AddRateLimiter with 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");

    Official documentation

  8. Q8. How do you run background work in ASP.NET Core, and what are the risks?

    Implement BackgroundService and register it with AddHostedService. Use a Channel<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.

    Official documentation

  9. 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") });

    Official documentation

  10. 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-Origin for 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 UseCors before authorization. Don't combine AllowAnyOrigin with AllowCredentials; 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");

    Official documentation

  11. 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 Select into a DTO (best, since it fetches only the needed columns), or use Include. Use AsNoTracking() 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);

    Official documentation

  12. 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 to appsettings.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.

    Official documentation

  13. 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.

    Official documentation

  14. Q14. What happens in Program.cs of an ASP.NET Core app?

    WebApplication.CreateBuilder sets up configuration, logging and the dependency injection container. You register services on builder.Services, then builder.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();
  15. 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.

  16. 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));
    }
  17. 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 with app.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>();
  18. 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.

  19. 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 into ModelState.

    With [ApiController], an invalid model automatically returns a 400 Bad Request with the errors, so you do not need to check ModelState.IsValid yourself. 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 invalid
  20. Q20. 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 :int make a route match only valid values, so /api/orders/abc returns 404 instead of reaching the action.

  21. 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. IActionResult lets you return different responses such as NotFound() or BadRequest(), but loses the type for API documentation.

    ActionResult<T> gives both: you can return T for 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;
    }
  22. Q22. What is the difference between authentication and authorization in ASP.NET Core?

    Authentication finds out who the user is, for example from a cookie or a JWT, and creates a ClaimsPrincipal. Authorization decides what that user may do, for example with [Authorize(Roles = "Admin")] or a policy.

    The middleware order matters: UseAuthentication() must come before UseAuthorization(), and both after UseRouting() when routing is called explicitly. A 401 response means not authenticated; a 403 means authenticated but not allowed.

  23. Q23. What is policy-based authorization and why is it better than checking roles everywhere?

    A policy is a named rule, registered once, that can check roles, claims or any custom requirement. Endpoints then say [Authorize(Policy = "CanRefund")] instead of repeating role lists.

    When the rule changes, you change it in one place. Custom requirements and handlers can also check resources, such as whether the user owns the order being edited.

    builder.Services.AddAuthorization(o =>
        o.AddPolicy("CanRefund", p => p.RequireClaim("department", "support", "finance")));
    
    [Authorize(Policy = "CanRefund")]
    public IActionResult Refund(int orderId) => Ok();
  24. 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_ENVIRONMENT variable. Code can check app.Environment.IsDevelopment(), for example to show the detailed error page only during development.

  25. 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 by OrderId.

    logger.LogWarning("Payment {PaymentId} failed for order {OrderId}", paymentId, orderId);
  26. Q26. Why should you use IHttpClientFactory to call other APIs?

    Creating a new HttpClient per call can run out of sockets, and a single static client can miss DNS changes. IHttpClientFactory manages 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}");
    }
  27. 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 ToListAsync with EF Core) and never block with .Result or .Wait(). Pass the request's CancellationToken so work stops when the client goes away.

  28. 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.

  29. 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() and app.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.

    Official documentation

  30. 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 an HttpClient, 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 WithWebHostBuilder and ConfigureTestServices.

    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);
        }
    }
  31. 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; }

    Official documentation

  32. 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);

    Official documentation

  33. 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.

    Official documentation

  34. 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.

    Official documentation

  35. 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.

    Official documentation

  36. Q37. What do UseHttpsRedirection and UseHsts do?

    UseHttpsRedirection redirects HTTP requests to HTTPS. UseHsts sends 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();

    Official documentation

  37. 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);
       });

    Official documentation

  38. Q39. What is the difference between Results and TypedResults in minimal APIs?

    Results.Ok(x) returns IResult, so the framework cannot see from the method signature which responses are possible. TypedResults.Ok(x) returns a concrete type such as Ok<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());

    Official documentation

  39. 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 });
    }

    Official documentation

  40. 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 };
    });

    Official documentation

  41. 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.

  42. 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 webapiaot template sets this up.

    Official documentation

  43. 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-counters to watch request rate, thread-pool queue length, GC and exceptions live, and dotnet-trace or a memory dump for deeper analysis. Fix one thing, measure again, and add a test or alert so it does not come back.

    Official documentation

  44. 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 become ValidationProblemDetails with the field errors. Never put stack traces in it outside Development.

    builder.Services.AddProblemDetails();
    
    var app = builder.Build();
    app.UseExceptionHandler();
    app.UseStatusCodePages();

    Official documentation

Original questions written to explain concepts; not taken from any certification exam. Spotted a mistake? See our corrections policy.