Skip to main content

Entry ASP.NET Web API Interview Questions

Curated Entry-level ASP.NET Web API interview questions for developers targeting entry positions. 39 questions available.

Last updated:

ASP.NET Web API Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of ASP.NET Web API interview questions and answers. This page contains expertly curated interview questions covering all aspects of ASP.NET Web API, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our ASP.NET Web API interview questions are designed to help you:

  • Understand core concepts and best practices in ASP.NET Web API
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next ASP.NET Web API interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic ASP.NET Web API concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

39 questions
Q1:

What is ASP.NET Core Web API and how does it differ from MVC?

Entry

Answer

ASP.NET Core Web API is a framework for building HTTP services that return JSON, XML, or other serialized data.

Differences from MVC:

  • No Razor or HTML rendering
  • Focused on RESTful services
  • Controller methods return data, not views
  • Routing is often attribute-based
Quick Summary: ASP.NET Core Web API builds HTTP APIs (REST) without the View layer. MVC includes Views for server-side HTML rendering. Web API returns JSON/XML data consumed by front-end apps, mobile clients, or other services. Both share the same middleware pipeline, DI, and routing infrastructure. Web API controllers inherit from ControllerBase (no View support); MVC from Controller.
Q2:

Explain the request pipeline in ASP.NET Core Web API.

Entry

Answer

The pipeline consists of middleware components that process HTTP requests in sequence:

  • Request enters server
  • Middleware handles tasks like authentication, logging, routing
  • Endpoint routing selects controller/action
  • Controller executes business logic
  • Response flows back through middleware
Quick Summary: The request pipeline is a chain of middleware components. Each middleware can inspect and modify the request, call the next middleware, and modify the response on the way back. Order matters - defined in Program.cs. For Web API: UseRouting -> UseAuthentication -> UseAuthorization -> MapControllers. Request flows forward through middleware, response flows backward.
Q3:

What are Controllers and how are they structured?

Entry

Answer

Controllers handle incoming HTTP requests.

  • Decorated with [ApiController] and [Route]
  • Contain action methods
  • Use dependency injection via constructor
  • Return IActionResult or data objects
Quick Summary: Controllers group related API endpoints. Each controller class inherits ControllerBase and is decorated with [ApiController] and [Route("api/[controller]")]. Action methods handle specific HTTP verbs ([HttpGet], [HttpPost], [HttpPut], [HttpDelete]). [ApiController] enables automatic model validation, attribute routing, and better error responses. Return IActionResult or ActionResult for typed responses.
Q4:

How does Attribute Routing work in Web API?

Entry

Answer

Attribute routing uses attributes to define URL patterns.

  • [Route("api/[controller]")] sets base route
  • [HttpGet], [HttpPost] define HTTP verbs
  • Supports route parameters, constraints, defaults
Quick Summary: Attribute routing maps HTTP requests to controller actions using attributes directly on methods. [Route("api/users/{id}")] defines the URL template. [HttpGet("{id}")] matches GET requests. Route parameters ({id}) bind to action parameters. Constraints: {id:int}, {name:alpha}. More explicit than convention-based routing - each endpoint's URL is visible right on the action method.
Q5:

Explain model binding and validation.

Entry

Answer

Model binding maps HTTP data to method parameters.

  • [FromBody] binds JSON/XML
  • [FromQuery] binds query parameters
  • [FromRoute] binds URL segments

Validation uses DataAnnotations and ModelState.IsValid.

Quick Summary: Model binding automatically maps HTTP request data (route params, query string, body, headers, form) to action method parameters. [FromBody] binds JSON request body. [FromQuery] binds query string. [FromRoute] binds route parameters. [FromHeader] binds headers. [ApiController] enables automatic validation - if ModelState is invalid, it returns 400 Bad Request without needing to check manually.
Q6:

What are Action Results and why are they important?

Entry

Answer

Action results allow APIs to return proper HTTP responses.

  • Return 200, 404, 400 etc.
  • Provide flexibility using IActionResult
  • Support multiple return formats
Quick Summary: Action Results are objects returned from controller actions that determine the HTTP response. Common: Ok(data) -> 200, Created(uri, data) -> 201, BadRequest(errors) -> 400, Unauthorized() -> 401, NotFound() -> 404, NoContent() -> 204. Use ActionResult as return type for both typed returns and IActionResult alternatives. They abstract HTTP status codes from business logic.
Q7:

What is Content Negotiation in Web API?

Entry

Answer

Content negotiation selects the response format based on:

  • Client's Accept header
  • Configured formatters (JSON, XML)

ASP.NET Core defaults to JSON.

Quick Summary: Content Negotiation lets the client specify what format it wants (JSON, XML) via the Accept header. The server checks available output formatters and picks the best match. ASP.NET Core includes JSON formatter by default. Add XML: services.AddControllers().AddXmlSerializerFormatters(). If no match: returns default format (406 Not Acceptable if configured strictly).
Q8:

How are dependency injection and services handled in Web API?

Entry

Answer

ASP.NET Core has built-in DI.

  • Register services using AddSingleton/AddScoped/AddTransient
  • Injected via controller constructor
  • Improves modularity and testability
Quick Summary: ASP.NET Core has built-in DI. Register services in Program.cs: builder.Services.AddScoped(). Controllers declare dependencies as constructor parameters - DI injects them automatically. This enables loose coupling, testability (inject mocks), and lifetime management. Never create services with new inside controllers - always inject via constructor.
Q9:

Explain the difference between Scoped, Singleton, and Transient lifetimes.

Entry

Answer

Singleton: One instance for entire app.

Scoped: One instance per request.

Transient: New instance per usage.

Quick Summary: Transient: new instance created every time it's requested (stateless, lightweight services). Scoped: one instance per HTTP request - shared within that request (EF Core DbContext). Singleton: one instance for the app lifetime - shared across all requests (config, caches). Never inject Scoped into Singleton - creates a captive dependency (the Scoped object lives longer than intended).
Q10:

How do you handle exceptions in Web API?

Entry

Answer

Best practices include:

  • UseExceptionHandler middleware
  • Exception filters
  • Centralized logging
  • Returning friendly error messages
Quick Summary: Exception handling options: try-catch in action methods, global exception handling middleware (IMiddleware or app.UseExceptionHandler()), or ProblemDetails pattern (RFC 7807). Exception filters catch exceptions from action execution. UseExceptionHandler is the recommended global approach - returns consistent error responses. Never expose stack traces in production.
Q11:

How does ASP.NET Core handle JSON serialization?

Entry

Answer

Uses System.Text.Json by default.

  • High performance
  • Supports converters and casing rules
  • Can switch to Newtonsoft.Json if required
Quick Summary: ASP.NET Core uses System.Text.Json by default (fast, low-allocation). Configure globally in AddControllers(options => ...). Options: JsonNamingPolicy.CamelCase, ReferenceHandler.Preserve for circular refs, custom converters for types like DateOnly. Newtonsoft.Json (AddNewtonsoftJson()) is optional for backwards compatibility. Use [JsonPropertyName("name")] to customize JSON property names per class.
Q12:

What are Action Filters and when do you use them?

Entry

Answer

Action filters run before/after actions.

  • Logging
  • Validation
  • Authentication
  • Response modification
Quick Summary: Action filters run code before/after action execution. Use for: logging, input validation, performance timing, caching headers. Implement IActionFilter (sync) or IAsyncActionFilter (async). OnActionExecuting runs before the action, OnActionExecuted runs after. Apply as [attribute] on controller or action, or register globally in MVC options. Different from middleware: filters have access to action context (controller, action name, parameters).
Q13:

Explain the purpose of FromBody, FromQuery, and FromRoute.

Entry

Answer

[FromBody] - reads body JSON/XML.

[FromQuery] - reads query string.

[FromRoute] - maps URL parameters.

Quick Summary: [FromBody]: deserializes JSON/XML request body into a parameter - use for POST/PUT with complex data. [FromQuery]: reads from URL query string (?name=Alice). [FromRoute]: reads from URL path template ({id}). [FromHeader]: reads from HTTP header. [FromForm]: reads from form data. Without these, [ApiController] uses smart inference: complex types default to [FromBody], primitives to [FromQuery].
Q14:

How do you implement versioning in Web API?

Entry

Answer

API versioning methods:

  • URL versioning: /api/v1/
  • Query string versioning
  • Header versioning (api-version)

Implemented using the Versioning package.

Quick Summary: API versioning strategies: URL path (/api/v1/users), query string (?api-version=1), headers (API-Version: 1). Use the Microsoft.AspNetCore.Mvc.Versioning package. [ApiVersion("1.0")] on controllers. Run multiple versions side by side. Deprecate old versions with [ApiVersion("1.0", Deprecated = true)]. URL path versioning is the most visible and REST-compatible approach.
Q15:

What is CORS and why is it important in Web API?

Entry

Answer

CORS allows cross-domain API access.

Configured using AddCors + middleware.

Needed for browser-based clients.

Quick Summary: CORS (Cross-Origin Resource Sharing) restricts which origins can make requests to your API from browsers. Configure in Program.cs: builder.Services.AddCors() and app.UseCors(). Define policies: AllowAnyOrigin(), WithOrigins("https://yourapp.com"), AllowAnyMethod(), AllowAnyHeader(). Apply globally or per controller/action. Allow only specific trusted origins - avoid AllowAnyOrigin in production.
Q16:

How do you secure a Web API?

Entry

Answer

Security techniques include:

  • JWT Bearer authentication
  • [Authorize] attributes
  • HTTPS enforcement
  • Input validation
  • Rate limiting
Quick Summary: Secure Web API: use JWT or OAuth2 for authentication. Enforce HTTPS. Apply [Authorize] to protect endpoints. Use CORS to restrict origins. Validate all inputs (model validation). Rate limit to prevent abuse. Return minimal error details (no stack traces). Keep dependencies updated. Use HTTPS-only cookies if using cookies. Apply principle of least privilege for service accounts and API keys.
Q17:

Explain the difference between synchronous and asynchronous controllers.

Entry

Answer

Synchronous: Thread waits for completion.

Asynchronous: Releases thread during I/O.

Async improves scalability.

Quick Summary: Synchronous controllers block a thread for the duration of I/O operations. Async controllers: use async Task return type and await I/O calls (DbContext, HttpClient). The thread is released during await, allowing the server to handle other requests. Under load, async prevents thread exhaustion. Rule: always use async for any controller that does I/O (database, HTTP, file).
Q18:

What is Response Caching in Web API?

Entry

Answer

Response caching reduces repeated processing.

  • Uses [ResponseCache] attribute
  • Decreases latency
  • Improves throughput
Quick Summary: Response caching stores HTTP responses to serve repeated requests faster. [ResponseCache] attribute sets Cache-Control headers telling clients/proxies how long to cache. UseResponseCaching() middleware caches on the server side. VaryByQueryKeys caches different versions per query parameter. Not suitable for user-specific or highly dynamic responses. Use distributed caching (Redis) for server-side caching of database results.
Q19:

How do you test a Web API effectively?

Entry

Answer

Testing involves:

  • Unit tests with mocks
  • Integration tests with TestServer
  • API testing tools (Postman, Swagger)
  • Validating status codes, payloads, headers
Quick Summary: Web API testing: unit tests with xUnit/NUnit + Moq (mock services, test action logic in isolation). Integration tests with WebApplicationFactory - spins up the real app with an in-memory or test database, makes HTTP calls with HttpClient. Test all HTTP verbs, status codes, error cases. Use TestServer for lightweight integration tests without a real HTTP server.
Q20:

Why is Swagger/OpenAPI important in Web API?

Entry

Answer

Swagger provides:

  • Interactive API documentation
  • Endpoint visibility
  • Contract testing
  • Client-code generation
Quick Summary: Swagger (OpenAPI) auto-generates interactive API documentation from your code. Developers can explore endpoints, see request/response schemas, and test calls directly in the browser. Add with Swashbuckle.AspNetCore. Integrate XML comments for detailed descriptions. Add JWT auth support in Swagger UI. Essential for API-first development and enabling frontend/mobile teams to understand the API contract.
Q21:

What is Middleware in ASP.NET Core Web API?

Entry

Answer

Middleware are components in the ASP.NET Core request pipeline that execute sequentially.

Each middleware can:

  • Process the request before passing it forward
  • Process the response after the next middleware has executed

Common examples include authentication, logging, CORS, and routing middleware.

Order is critical because each middleware depends on the sequence.

Quick Summary: Middleware is a component in the request pipeline that processes HTTP requests and responses. Each middleware calls next() to pass control forward. Custom middleware: implement IMiddleware or write a request delegate (async (context, next) => {...}). Register with app.UseMiddleware(). Order matters - authentication must run before authorization, error handling must be first.
Q22:

How does the UseRouting and UseEndpoints middleware work?

Entry

Answer

UseRouting identifies the matching endpoint based on the URL.

UseEndpoints executes the matched action.

Authentication, authorization, and CORS middleware should be placed between these two for correct behavior.

Quick Summary: UseRouting() matches the incoming request URL to an endpoint (stores the match in HttpContext). UseEndpoints() (or MapControllers()) executes the matched endpoint. Middleware between UseRouting and UseEndpoints has access to the matched endpoint info (e.g., UseAuthorization can read [Authorize] attributes on the matched action). Without UseRouting first, authorization can't know which endpoint was matched.
Q23:

How do you create custom middleware?

Entry

Answer

Custom middleware involves:

  • Create a class with a constructor accepting RequestDelegate
  • Implement Invoke or InvokeAsync
  • Register with app.UseMiddleware<T>()
Quick Summary: Custom middleware: write an async method with (HttpContext context, RequestDelegate next) parameters, or implement IMiddleware. Call await next(context) to continue pipeline. Modify request before, response after. Register: app.Use(async (context, next) => {...}) or app.UseMiddleware(). Use for: request logging, adding headers, timing, IP filtering - anything that applies to all requests.
Q24:

Explain Filters in ASP.NET Core Web API.

Entry

Answer

Filters run during the execution pipeline and include:

  • Authorization Filters
  • Resource Filters
  • Action Filters
  • Exception Filters
  • Result Filters
Quick Summary: ASP.NET Core filters run at specific points around action execution. Types: Authorization (first - can short-circuit), Resource (before/after model binding), Action (before/after action runs), Exception (handles unhandled exceptions), Result (before/after result executes). Filters are MVC-specific (have access to action context) while middleware applies to all requests including static files.
Q25:

How is model validation applied automatically?

Entry

Answer

Applying [ApiController] automatically triggers model validation.

Invalid models result in 400 Bad Request with error details.

Validation uses DataAnnotations like [Required], [Range], etc.

Quick Summary: [ApiController] attribute enables automatic model validation: if ModelState.IsValid is false after model binding, it automatically returns 400 Bad Request with validation error details - no manual check needed. Define validation with DataAnnotations ([Required], [MaxLength], [EmailAddress]) or FluentValidation. Customize the 400 response using InvalidModelStateResponseFactory in MVC options.
Q26:

How do you implement global exception handling using middleware?

Entry

Answer

Global exception handling steps:

  • Create custom exception middleware
  • Wrap request processing in try/catch
  • Log and return a standardized error response
  • Use app.UseExceptionHandler() for production mode
Quick Summary: Global exception handling with middleware: app.UseExceptionHandler(app => app.Run(async context => { var error = context.Features.Get(); log error; await context.Response.WriteAsJsonAsync(new ProblemDetails {...}); })). In .NET 8: use IExceptionHandler interface and app.AddExceptionHandler(). Returns RFC 7807 ProblemDetails format. Always handle exceptions globally - don't rely on developers to try-catch everywhere.
Q27:

Explain the difference between synchronous and asynchronous middleware.

Entry

Answer

Synchronous middleware: Blocks thread while executing.

Asynchronous middleware: Uses Task and await to release thread during I/O operations.

Async middleware improves scalability in high-load systems.

Quick Summary: Synchronous middleware blocks the thread for its duration. Async middleware uses async/await to release the thread during I/O waits. Use async middleware for any I/O in the pipeline (logging to a service, reading from Redis, DB calls). Synchronous middleware in async pipelines can cause thread pool starvation under load. Always write middleware as async unless it has no I/O.
Q28:

How can you implement logging in Web API?

Entry

Answer

Logging methods:

  • Use ILogger<T> via DI
  • Log levels: Trace ? Critical
  • Send logs to Console, Files, DB, or external providers
  • Use middleware/filters for request & response logging
Quick Summary: ASP.NET Core logging: inject ILogger via DI. Log with logger.LogInformation(), LogWarning(), LogError(). Configure providers in appsettings.json (Console, File via Serilog/NLog, Application Insights). Use structured logging: logger.LogInformation("User {UserId} logged in", userId) - preserves the userId as a queryable field. Serilog or NLog for file sinks and centralized logging.
Q29:

What is diagnostic middleware and why is it important?

Entry

Answer

Diagnostic middleware provides insights into requests and system behavior.

Examples: DeveloperExceptionPage, SerilogRequestLogging, Application Insights.

Helps detect failures, anomalies, and performance issues.

Quick Summary: Diagnostic middleware provides insights into request processing. UseDeveloperExceptionPage() shows detailed error info in development. UseStatusCodePages() adds custom responses for 404/500. Built-in health check middleware (UseHealthChecks) reports app status. Custom diagnostics middleware can log request/response details, timing, and add correlation IDs to all requests for distributed tracing.
Q30:

How do you handle CORS in a Web API?

Entry

Answer

CORS is configured using:

  • AddCors() in Program.cs
  • Define policies with allowed origins, headers, and methods
  • Apply globally or per controller using [EnableCors]
Quick Summary: Handle CORS: add services (AddCors), define a named policy with allowed origins, methods, headers. Apply policy globally (app.UseCors("MyPolicy")), per controller ([EnableCors("MyPolicy")]), or per action. For credentials (cookies, auth headers): call AllowCredentials() and specify exact origins (not wildcard). UseResponseCaching middleware needs CORS configured before it.
Q31:

How do you restrict content types in requests?

Entry

Answer

Use the [Consumes] attribute:

[Consumes("application/json")]

Rejects unsupported media types with HTTP 415.

Quick Summary: Restrict content types with a custom action filter or resource filter that checks request Content-Type header. Reject requests with unsupported content types (return 415 Unsupported Media Type). [Consumes("application/json")] attribute on action methods declares what content types are accepted and restricts routing to matching requests. Prevents processing unexpected content formats.
Q32:

How do you inspect and log request/response bodies safely?

Entry

Answer

To log safely:

  • Use EnableBuffering() for reading request body
  • Wrap the response stream to capture outgoing body
  • Avoid logging sensitive data
Quick Summary: Log request/response bodies: use middleware that buffers the request body (EnableBuffering() to make it re-readable), reads and logs it, then resets the stream position. For responses: replace the original response body stream with a MemoryStream, let the pipeline write to it, log it, then copy to the original. Be careful: don't log sensitive data (passwords, tokens). Limit logged body size.
Q33:

What is the difference between endpoint routing and legacy MVC routing?

Entry

Answer

Endpoint routing: Pre-matches endpoints before controller activation.

Legacy routing: Occurred during MVC action selection.

Endpoint routing is more flexible and enables better middleware integration.

Quick Summary: Endpoint routing (current): UseRouting() matches routes, UseEndpoints() executes them. Middleware in between can inspect the matched endpoint. Supports any endpoint type (controllers, Razor pages, gRPC, health checks). Legacy MVC routing: route matching done inside MVC itself, no separation. Endpoint routing is more flexible, allows authorization to read endpoint metadata before execution.
Q34:

How do you implement API versioning?

Entry

Answer

Use API Versioning package.

  • URL versioning
  • Header versioning
  • Query string versioning

Decorate controllers with [ApiVersion("1.0")].

Quick Summary: API versioning with Microsoft.AspNetCore.Mvc.Versioning: AddApiVersioning() in services. [ApiVersion("1.0")] on controllers. URL path: v1/api/users, query string: ?api-version=1, header: api-version: 1. MapToApiVersion(1.0) maps actions to specific versions. Return supported versions in API-Supported-Versions response header. Deprecate old versions gracefully with documentation.
Q35:

How do you configure JSON serialization globally?

Entry

Answer

Configure using:

AddControllers().AddJsonOptions(options => { ... });

Supports camelCase, converters, and null handling.

Quick Summary: Configure JSON globally: builder.Services.AddControllers().AddJsonOptions(opts => { opts.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; opts.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }). Add custom converters for complex types. Override per controller with [JsonOptions].
Q36:

How do you handle API response formatting?

Entry

Answer

Use IActionResult or ActionResult<T> for flexible responses.

Supports content negotiation and custom response formatting.

Quick Summary: Handle API response formatting: return typed ActionResult for auto-serialization. Use ProducesResponseType attributes for Swagger documentation. Set Content-Type in responses. Implement custom output formatters for non-JSON formats. Use ProblemDetails for error responses (RFC 7807 standard). Consistent response structure: always include status, data, and error fields for predictable client handling.
Q37:

How do you throttle requests in ASP.NET Core Web API?

Entry

Answer

Use libraries like AspNetCoreRateLimit.

  • Define IP or user-based rate limits
  • Prevent abuse and DoS attacks
  • Supports rule-based throttling
Quick Summary: Rate limiting in ASP.NET Core 7+: built-in RateLimiter middleware. Policies: FixedWindowLimiter, SlidingWindowLimiter, TokenBucketLimiter, ConcurrencyLimiter. Add with AddRateLimiter(). Apply globally or per endpoint with [EnableRateLimiting("policy")]. Returns 429 Too Many Requests with Retry-After header. Identify clients by IP, user ID, or API key for per-client limits.
Q38:

What are dependency injection best practices in Web API?

Entry

Answer

Best practices:

  • Use correct lifetimes: Singleton, Scoped, Transient
  • Prefer constructor injection
  • Avoid service locator pattern
  • Group and organize service registrations
Quick Summary: DI best practices: program to interfaces (inject IRepository, not Repository). Use Scoped for request-scoped state (DbContext, user context). Use Singleton for shared stateless services (HttpClient via IHttpClientFactory, configuration). Never capture Scoped in Singleton. Use AddHttpClient() for HttpClient (manages connection pooling). Avoid service locator pattern (don't inject IServiceProvider to call GetService manually).
Q39:

How do you monitor Web API performance in production?

Entry

Answer

Use monitoring platforms like:

  • Application Insights
  • Serilog + Seq
  • ELK Stack
  • Prometheus + Grafana

Track latency, errors, throughput, and resource usage.

Quick Summary: Monitor Web API: Application Insights (auto-collects requests, dependencies, exceptions, performance counters). Health checks endpoint (/health) for load balancer probes. Prometheus + Grafana for metrics. Structured logging with Serilog to ELK/Seq. Key metrics: request rate, error rate, latency (p95/p99), DB query time, thread pool size. Set up alerts on error rate spikes and latency degradation.

Curated Sets for ASP.NET Web API

No curated sets yet. Group questions into collections from the admin panel to feature them here.

Ready to level up? Start Practice