ASP.NET Web API interview questions and answers

ASP.NET Web API interview questions check whether you can build HTTP APIs in .NET that behave correctly at the edges: the right status codes, clean validation errors, safe authentication and predictable versioning. Expect the ApiController attribute and what it switches on, ActionResult of T versus IActionResult, where model binding reads each value from, ProblemDetails, content negotiation, filters and integration testing. Many teams also ask how classic Web API 2 differs from ASP.NET Core, because both still run in production.

By Published 7 min read

Which Web API the interviewer means

"Web API" in a .NET job post can mean two stacks. ASP.NET Web API 2 runs on .NET Framework with System.Web.Http, an ApiController base class and IIS or OWIN hosting. ASP.NET Core merged MVC and Web API into one framework, where API controllers derive from ControllerBase and carry the ApiController attribute. Most new code is ASP.NET Core, but many companies still maintain Web API 2 services, so ask which one the team runs and answer for that. General HTTP and resource design questions are covered in REST API interview questions; this page stays on the .NET framework side.

  • Phone or online screen: short questions on controllers, routing, status codes and binding.
  • Code exercise: build or fix a small CRUD controller, often with validation, paging and a test.
  • Code review: a controller with problems such as sync-over-async, leaked exceptions or a missing authorization check.
  • Design discussion for seniors: versioning, error contracts, idempotency, rate limits and how clients will call it.

Fundamentals questions

Questions for juniors and first screens
QuestionWhat it testsWhat a strong answer shows
What does the ApiController attribute change?ConventionsIt requires attribute routing, returns 400 automatically when model state is invalid, infers binding sources (complex types from the body, simple ones from route or query), and shapes error responses as ProblemDetails.
ControllerBase versus Controller?Base classesControllerBase has everything an API needs: Ok, NotFound, CreatedAtAction and so on. Controller adds view support for MVC pages, which an API does not need.
IActionResult versus ActionResult of T?Return typesIActionResult can return any result but hides the success type. ActionResult of T lets you return either a T or a result like NotFound, and tools such as OpenAPI generators can see the response type.
What status code should a create return?HTTP semantics201 Created with a Location header pointing to the new resource, which CreatedAtAction builds from a route name and id, and usually the created body.
What are binding source attributes?Model bindingFromRoute, FromQuery, FromBody, FromHeader, FromForm and FromServices state where a parameter comes from. Only one parameter can be read from the body.
How does attribute routing work?RoutingRoute templates on the controller and actions, with tokens like [controller] and constraints like {id:int}. Constraints narrow matching; they are not input validation.
How do you validate input?ValidationData annotations such as Required, Range and StringLength, IValidatableObject for cross-field rules, or a validation library the team chooses. With ApiController, invalid input never reaches the action.
What is content negotiation?FormattingThe framework picks an output formatter from the Accept header. JSON is the default; XML needs a formatter added. You can make unsupported types return 406 instead of falling back to JSON.
What is HttpResponseMessage in Web API 2?Classic stackThe raw response object classic actions could return, giving full control of status, headers and content. IHttpActionResult arrived in Web API 2 to make that testable.
Where do filters fit?PipelineAuthorization, resource, action, exception and result filters run around the action inside the MVC pipeline, after middleware. Use them for concerns tied to actions, middleware for everything else.
Questions for juniors and first screens. Scroll sideways on a small screen.
public record CreateOrder(
    [Required, StringLength(40)] string CustomerId,
    [Range(1, 500)] int Quantity);

public record OrderDto(int Id, string CustomerId, int Quantity);

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    private readonly IOrderStore _store;
    public OrdersController(IOrderStore store) => _store = store;

    [HttpGet("{id:int}", Name = "GetOrder")]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<OrderDto>> Get(int id, CancellationToken ct)
    {
        var order = await _store.FindAsync(id, ct);
        if (order is null) return NotFound();
        return order;
    }

    [HttpPost]
    [Authorize(Policy = "orders:write")]
    public async Task<ActionResult<OrderDto>> Create(
        CreateOrder input,
        [FromHeader(Name = "Idempotency-Key")] string? idempotencyKey,
        CancellationToken ct)
    {
        var order = await _store.CreateAsync(input, idempotencyKey, ct);
        return CreatedAtRoute("GetOrder", new { id = order.Id }, order);
    }
}
An ASP.NET Core controller with binding sources, validation, cancellation and the usual results. Not executed (no .NET SDK on this machine); IOrderStore is a placeholder for your data layer.

Intermediate questions

  • What is ProblemDetails? A standard JSON error shape with type, title, status, detail and instance fields, defined in an IETF RFC. ASP.NET Core can produce it for validation errors and, with the problem details service and exception handler middleware, for unhandled errors too, so clients parse one format.
  • How do you handle exceptions globally? Use the exception handler middleware or an exception filter, log with a correlation id, return a ProblemDetails body, and never send stack traces to clients outside development.
  • Why accept a CancellationToken in actions? The framework binds it to the request being aborted. Passing it to database and HTTP calls stops wasted work when a client disconnects or times out.
  • What goes wrong with .Result or .Wait() in an action? It blocks a thread pool thread while waiting, which under load starves the pool and slows everything. In classic ASP.NET it could also deadlock because of the synchronization context.
  • How do you return a list that might be large? Page it with limit and cursor or page parameters, cap the page size on the server, and return paging metadata. Streaming with IAsyncEnumerable is an option for genuine bulk exports.
  • How do you set up JWT bearer authentication? Register the JWT bearer handler with the issuer, audience and signing keys (usually from the identity provider's metadata), add UseAuthentication before UseAuthorization, then protect actions with Authorize and named policies over scopes or roles.
  • Authentication versus authorization in this framework? Authentication builds the user principal from the token. Authorization decides with attributes, policies and requirement handlers whether that principal may run this action or touch this resource.
  • How does CORS work here? A browser sends a preflight OPTIONS request for many cross-origin calls. You register named CORS policies with allowed origins, methods and headers, and apply them in the right place in the middleware order. CORS protects browsers, not your API from other clients.
  • How would you version an API? Choose URL segment, query string or header versioning, usually with the Asp.Versioning packages, mark old versions deprecated, report supported versions in headers, and keep contract tests per version.
  • How do you document the API? Generate an OpenAPI document from controllers with Swashbuckle, NSwag or the newer built-in OpenAPI support, enrich it with ProducesResponseType and XML comments, and check it in CI so the contract does not drift.
  • Why use IHttpClientFactory for outgoing calls? Creating and disposing HttpClient per request can exhaust sockets, while one static client can miss DNS changes. The factory pools handlers, and typed clients let you add timeouts and retry policies in one place.
  • PUT versus PATCH in a .NET API? PUT replaces the whole resource, so missing fields mean cleared values. PATCH applies a partial change, either as a JSON Patch document or a merge-style body, and needs care to tell an omitted field from an explicit null.
  • How would you cache GET responses? Send Cache-Control and ETag headers so clients and proxies can reuse responses, and use server-side output or response caching only for data that is safe to share between users. Never cache responses that vary by the caller's identity without keying on it.
  • What does the rate limiting middleware do? It applies limiters such as fixed window, sliding window, token bucket or concurrency to endpoints or policies and returns 429 when a client exceeds them. It is available built in on recent ASP.NET Core versions.

Senior and scenario questions

Questions for experienced .NET API developers
QuestionWhat it testsWhat a strong answer shows
A mobile client retried a POST and created two orders. Fix it.IdempotencyAccept an idempotency key header, store it with the result in the same transaction, and return the stored response on repeats. Also add a unique constraint where the business allows.
Two users edit the same record and one overwrite is lost. What do you add?ConcurrencyOptimistic concurrency with an ETag or row version: return it on GET, require If-Match on PUT or PATCH, and send 412 when it no longer matches.
The API got slow after a release but CPU is fine. Where do you look?DiagnosisThread pool starvation from blocking calls, a missing CancellationToken, a new N+1 query, a downstream call without a timeout, or connection pool exhaustion. Traces and dependency timings settle it.
How would you move a Web API 2 service to ASP.NET Core?MigrationInventory message handlers, filters, formatters and OWIN middleware, map each to middleware or filters, keep routes and JSON settings identical, and compare responses side by side before switching traffic.
JSON property names changed after the migration. Why?SerializationClassic Web API used Newtonsoft.Json with its settings; ASP.NET Core defaults to System.Text.Json with camelCase and different rules. Set the options explicitly or add the Newtonsoft formatter.
How do you test controllers?TestingUnit test logic in services, and test the HTTP surface with WebApplicationFactory, which runs the app in memory with test doubles so routing, binding, auth and status codes are checked together.
How do you keep error responses consistent across 30 controllers?DesignOne exception-to-ProblemDetails mapping, the ApiController validation response, shared result helpers, and an OpenAPI check that every endpoint declares its errors.
When would you not use controllers?JudgmentSmall services or high-throughput endpoints may suit minimal APIs, which the .NET interview questions page compares. Controllers still help larger teams with filters, conventions and structure.
Questions for experienced .NET API developers. Scroll sideways on a small screen.

Fictional example

Answering "Design the error responses for our public API."
Interviewer
Partners complain that our API errors come back in five different shapes. What would you do?
Candidate
I would standardize on ProblemDetails so every error has the same fields: a type URI that documents the error, a title, the status code, a detail message and a trace id for support. Validation errors would keep the framework's automatic 400 with field-level messages. Unhandled exceptions would go through the exception handler, logged with the trace id and returned as a 500 with no internals. Domain errors such as an insufficient balance would map to specific types and to 409 or 422, decided once in a shared mapper rather than in each controller. Then I would document every type in the OpenAPI file and add a test that fails if an endpoint returns an undocumented error. For partners, I would announce the change as a new API version so nobody's parser breaks overnight.

A practice plan for Web API rounds

  1. Build a small API from memoryOrders or tickets with GET, POST, PUT and DELETE, validation, 201 with Location, 404 and paging.
  2. Add the production layerJWT bearer auth with one policy, CORS for a single origin, a rate limit, and ProblemDetails for every error.
  3. Write three integration testsUse WebApplicationFactory to check a validation failure, an unauthorized call and a successful create.
  4. Rehearse two storiesOne bug you fixed in an API and one design decision you would make differently now, each in under two minutes.

Older services you inherit may still speak SOAP; WCF interview questions cover that side, and ASP.NET MVC interview questions cover the page-rendering half of the same pipeline. If an integration platform sits between your API and other systems, see webMethods interview questions.

Web API interviews reward exact answers about status codes, binding and middleware order. Natively, an AI interview assistant for Mac and Windows, keeps a transcript of a mock API round on your computer, so you can catch where you said 200 when you meant 201. In practice it can read a controller or a failing test from a screenshot and offer coding help, and with Pro or the free trial it tailors suggestions to the résumé and job description you add. Your notes and transcripts remain for review.

Questions people ask

What Web API questions are asked in .NET interviews?

What the ApiController attribute does, ControllerBase versus Controller, ActionResult of T, binding sources, validation and ProblemDetails, content negotiation, JWT bearer authentication, CORS, versioning, HttpClientFactory and integration testing.

What is the difference between ASP.NET Web API and ASP.NET Core Web API?

ASP.NET Web API 2 runs on .NET Framework with System.Web.Http and IIS or OWIN hosting. ASP.NET Core merged MVC and Web API into one cross-platform framework where API controllers derive from ControllerBase.

What does the ApiController attribute do?

It requires attribute routing, returns an automatic 400 when model validation fails, infers where parameters are bound from, and formats error responses as ProblemDetails.

Should a Web API return IActionResult or ActionResult of T?

ActionResult of T is usually better when there is a success type, because it can return either the object or a result like NotFound and documentation tools can see the response type.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP