Skip to content

ASP.NET Core Web API Interview Questions for .NET Full Stack

25 ASP.NET Core Web API questions with answers for .net full stack roles — 7 easy, 13 medium, 5 hard.

About ASP.NET Core Web API

Building production REST APIs with ASP.NET Core: middleware, dependency injection lifetimes, routing, controllers and Minimal APIs, model validation, filters, global error handling, configuration, logging, caching, rate limiting, CORS and JWT authentication. Scenario questions focus on securing, scaling and troubleshooting APIs used by web and mobile clients.

Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is ASP.NET Core and what are its main features?

Save to ▾
Show answer
ASP.NET Core is the open-source, cross-platform framework for building web APIs, MVC sites, Razor Pages, Blazor apps and real-time apps with SignalR on modern .NET. Key features are built-in dependency injection, a configurable middleware pipeline, the fast Kestrel web server, unified configuration and logging, and support for Docker and cloud hosting. It runs on Windows, Linux and macOS and consistently ranks among the fastest web frameworks.
02

What is the middleware pipeline in ASP.NET Core?

Save to ▾
Show answer
Every HTTP request passes through a chain of middleware components configured in Program.cs. Each component can inspect or modify the request, call the next one, and then work on the response on the way back. Order matters: exception handling first, then HTTPS redirection, static files, routing, CORS, authentication, authorization and finally endpoints. For example, putting UseAuthorization before UseAuthentication means users never appear logged in.
03

Explain the transient, scoped and singleton service lifetimes.

Save to ▾
Show answer
Transient services are created every time they are requested, suitable for lightweight stateless helpers. Scoped services are created once per HTTP request and shared within it; DbContext is registered as scoped. Singleton services are created once for the whole application lifetime, suitable for caches and configuration. Choose based on state: anything holding per-request data must not be singleton, and singletons must be thread-safe.
04

Show attribute routing for a products controller with route constraints.

Save to ▾
Show answer
[ApiController] [Route("api/[controller]")] public class ProductsController(IProductService service) : ControllerBase { [HttpGet] public async Task<IActionResult> GetAll() => Ok(await service.GetAllAsync()); [HttpGet("{id:int}")] public async Task<IActionResult> Get(int id) { var p = await service.GetAsync(id); return p is null ? NotFound() : Ok(p); } [HttpPost] public async Task<IActionResult> Create(ProductDto dto) { var created = await service.CreateAsync(dto); return CreatedAtAction(nameof(Get), new { id = created.Id }, created); } }
05

What is the difference between authentication and authorization in ASP.NET Core?

Save to ▾
Show answer
Authentication answers who you are: middleware reads a cookie or JWT, validates it and builds a ClaimsPrincipal for HttpContext.User. Authorization answers what you may do: it checks that user against rules such as [Authorize(Roles = "Admin")] or a policy like requiring an Employee claim with a certain department. A missing or invalid identity gives 401 Unauthorized, while a valid user without permission gets 403 Forbidden.
06

What is CORS and how do you enable it in ASP.NET Core?

Save to ▾
Show answer
Browsers block JavaScript from calling an API on a different origin (scheme, host or port) unless the server allows it via CORS headers. If an Angular app on localhost:4200 calls an API on localhost:5001, you add a policy with builder.Services.AddCors, allowing that origin with WithOrigins, plus required methods and headers, and call app.UseCors before authorization. Avoid AllowAnyOrigin in production, especially with credentials.
07

Which HTTP status codes and methods should a REST API use, and what is the difference between PUT and PATCH?

Save to ▾
Show answer
GET reads, POST creates, PUT replaces, PATCH partially updates and DELETE removes. Return 200 OK for success with a body, 201 Created with a Location header after POST, 204 No Content after delete, 400 for invalid input, 401 unauthenticated, 403 forbidden, 404 not found, 409 conflict and 500 for server errors. PUT sends the full resource and is idempotent; PATCH sends only changed fields.
08

Write custom middleware that logs how long each request takes.

Save to ▾
Show answer
public class TimingMiddleware(RequestDelegate next, ILogger<TimingMiddleware> logger) { public async Task InvokeAsync(HttpContext context) { var sw = Stopwatch.StartNew(); await next(context); sw.Stop(); logger.LogInformation("{Method} {Path} -> {Status} in {Ms} ms", context.Request.Method, context.Request.Path, context.Response.StatusCode, sw.ElapsedMilliseconds); } } // Program.cs app.UseMiddleware<TimingMiddleware>(); Code before next runs on the request, code after it runs on the response.
09

What is the difference between controllers and Minimal APIs?

Save to ▾
Show answer
Controllers group actions into classes with attributes for routing, filters and model binding, which suits large APIs with many conventions. Minimal APIs map endpoints directly with app.MapGet and lambdas, with less ceremony and slightly better performance, ideal for microservices and small APIs. Since .NET 7 they support filters, route groups and OpenAPI, and .NET 10 adds built-in validation, so both are production-ready choices.
10

How do model binding and validation work in ASP.NET Core Web API?

Save to ▾
Show answer
Model binding maps request data into action parameters from the route, query string, headers or body, using [FromRoute], [FromQuery] and [FromBody]. Validation uses data annotations like [Required], [StringLength] and [Range] on DTOs. With [ApiController], invalid models automatically return 400 Bad Request with ProblemDetails listing the errors, so you do not need to check ModelState manually. FluentValidation is popular for complex rules.
11

What types of filters exist in ASP.NET Core MVC?

Save to ▾
Show answer
Authorization filters run first and can block a request. Resource filters run before model binding, useful for caching. Action filters run before and after an action, for logging or validation. Exception filters handle errors thrown by actions. Result filters run around the result execution, for example to add headers. Filters apply globally, per controller or per action. Unlike middleware, they can access MVC details like action arguments.
12

Implement global exception handling that returns ProblemDetails.

Save to ▾
Show answer
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler { public async ValueTask<bool> TryHandleAsync(HttpContext ctx, Exception ex, CancellationToken ct) { logger.LogError(ex, "Unhandled error"); var status = ex is KeyNotFoundException ? 404 : 500; ctx.Response.StatusCode = status; await ctx.Response.WriteAsJsonAsync(new ProblemDetails { Status = status, Title = status == 404 ? "Not found" : "Server error" }, ct); return true; } } // Program.cs builder.Services.AddExceptionHandler<GlobalExceptionHandler>(); builder.Services.AddProblemDetails(); app.UseExceptionHandler();
13

Configure JWT bearer authentication in an ASP.NET Core API.

Save to ▾
Show answer
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(o => { o.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = builder.Configuration["Jwt:Issuer"], ValidAudience = builder.Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)) }; }); builder.Services.AddAuthorization(); app.UseAuthentication(); app.UseAuthorization(); Then protect endpoints with [Authorize] or [Authorize(Roles = "Admin")].
14

Show how to bind configuration from appsettings.json using the Options pattern.

Save to ▾
Show answer
// appsettings.json // "Smtp": { "Host": "smtp.example.com", "Port": 587 } public class SmtpOptions { public string Host { get; set; } = ""; public int Port { get; set; } } builder.Services.Configure<SmtpOptions>(builder.Configuration.GetSection("Smtp")); public class EmailService(IOptions<SmtpOptions> options) { private readonly SmtpOptions _smtp = options.Value; } appsettings.{Environment}.json and environment variables override base values. Use IOptionsMonitor to pick up changes without restart.
15

How does logging work in ASP.NET Core?

Save to ▾
Show answer
ASP.NET Core has a built-in ILogger<T> abstraction injected into any class. You log with levels Trace, Debug, Information, Warning, Error and Critical, and configure minimum levels per category in appsettings.json. Use structured logging with message templates, like logger.LogInformation("Order {OrderId} placed", id), so values become searchable fields. Providers such as Serilog or OpenTelemetry send logs to files, Seq, Elasticsearch or Application Insights.
16

An API creates a new HttpClient inside a using block for every outgoing call, and under load you see socket exhaustion errors. How do you fix it?

Save to ▾
Show answer
Disposing HttpClient does not immediately free the underlying socket; connections stay in TIME_WAIT, so thousands of short-lived clients exhaust ports. A single static client fixes that but misses DNS changes. The recommended fix is IHttpClientFactory: register builder.Services.AddHttpClient<PaymentClient>() and inject the typed client. The factory pools and rotates handlers, and you can add resilience with Microsoft.Extensions.Http.Resilience for retries and timeouts.
17

You must change an API response format, but an older mobile app version still calls it. How do you avoid breaking those users?

Save to ▾
Show answer
Versioning lets you change contracts without breaking existing clients such as mobile apps that users have not updated. Common approaches are URL segments (/api/v1/orders), query strings (?api-version=2.0) and headers. The Asp.Versioning library supports all of them and integrates with OpenAPI docs. URL versioning is the most visible and cache-friendly. Keep old versions running for a published period, then deprecate them with headers.
18

Describe an API you designed end to end and the decisions you made.

Save to ▾
Show answer
In my last project (Situation) we needed a leave-management API for 3,000 employees. My task was the full design. I modelled resources like /employees/{id}/leaves, used DTOs separate from EF entities, JWT with role policies for managers, FluentValidation, ProblemDetails errors and paging on every list. I documented it in OpenAPI and agreed the contract with the Angular team first. Result: front and back ends were built in parallel and launched on time.
19

Where should you store secrets like connection strings and API keys in an ASP.NET Core app?

Save to ▾
Show answer
Never commit them in appsettings.json. During development use the Secret Manager (dotnet user-secrets), which stores them outside the project folder. In production use environment variables or, better, a vault such as Azure Key Vault or AWS Secrets Manager, loaded through a configuration provider and accessed with managed identity so no credential sits in code. Rotate secrets regularly and restrict who can read them.
20

Tell me about a disagreement with the front-end team over an API contract and how you resolved it.

Save to ▾
Show answer
On a dashboard feature (Situation) the React team wanted one endpoint returning everything, while I worried about payload size. My task was to agree a design quickly. I set up a short call, we listed exact screen needs, and I proposed one aggregated endpoint with paging and optional fields. We wrote the OpenAPI spec together. Result: payload dropped by half, the UI got one call, and the spec became our template for later features.
21

A singleton CacheService injects AppDbContext, and users start seeing stale data and occasional 'a second operation was started on this context' errors. What is wrong?

Save to ▾
Show answer
This is a captive dependency: a scoped DbContext is captured by a singleton, so one context lives forever and is shared by all requests across threads. DbContext is not thread-safe and its change tracker grows stale. Fix it by injecting IServiceScopeFactory or IDbContextFactory<AppDbContext> into the singleton and creating a short-lived context per operation. Enabling ValidateScopes in development catches this at startup.
22

Your product API runs on four instances behind a load balancer and needs caching. Which ASP.NET Core caching options would you consider?

Save to ▾
Show answer
IMemoryCache stores data in the server's memory, fast but not shared across instances. IDistributedCache uses Redis or SQL Server so all instances share the cache. HybridCache, added in .NET 9, combines an in-memory layer with a distributed one and prevents cache stampedes. Output caching stores whole HTTP responses on the server, while response caching sets HTTP headers for browsers and proxies. Always set expiry and invalidate when data changes.
23

Add rate limiting to a login endpoint in ASP.NET Core.

Save to ▾
Show answer
builder.Services.AddRateLimiter(o => { o.RejectionStatusCode = StatusCodes.Status429TooManyRequests; o.AddPolicy("login", ctx => RateLimitPartition.GetFixedWindowLimiter( ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(1) })); }); app.UseRateLimiter(); app.MapPost("/api/login", LoginHandler).RequireRateLimiting("login"); Each IP gets 5 attempts per minute, which slows brute-force attacks. Behind a proxy, use the forwarded client IP.
24

Your product API must handle a festive sale with 10 times normal traffic. How do you prepare it?

Save to ▾
Show answer
Make the API stateless so you can scale it horizontally behind a load balancer or Kubernetes autoscaler. Cache read-heavy data such as product details in Redis or HybridCache. Ensure all I/O is async and database queries are indexed, projected and paged. Move slow work like emails to queues. Add rate limiting, timeouts and circuit breakers to dependencies, then load test with k6 or JMeter and watch metrics.
25

Access tokens in your app expire in 15 minutes and users complain about being logged out. How do you implement refresh tokens securely?

Save to ▾
Show answer
Issue a short-lived JWT access token plus a long-lived, random refresh token stored hashed in the database with expiry and device info. When the access token expires, the client calls /refresh with the refresh token; the server validates it, revokes it and issues a new pair, which is rotation. Reuse of a revoked token signals theft, so revoke the whole chain. In browsers, store the refresh token in an HttpOnly, Secure, SameSite cookie.

Frequently asked questions

How important is ASP.NET Core Web API in .NET Full Stack interviews?

Building production REST APIs with ASP.NET Core: middleware, dependency injection lifetimes, routing, controllers and Minimal APIs, model validation, filters, global error handling, configuration, logging, caching, rate limiting, CORS and JWT authentication. Scenario questions focus on securing, scaling and troubleshooting APIs used by web and mobile clients.

How should I use the ASP.NET Core Web API sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.