ASP.NET Web API (.NET Framework) Interview Questions
Answers written to be said out loud in an interview — each with a common follow-up question and a link to the tutorial that explains it in depth.
- Beginner
- 6
- Intermediate
- 11
- Experienced
- 6
01What is ASP.NET Web API 2?Beginner
A framework on .NET Framework for building HTTP services. Controllers derive from ApiController, routing is configured in WebApiConfig, and it is typically hosted on IIS.
02What is IHttpActionResult?Beginner
An interface returned from actions that represents an HTTP response, with helpers such as Ok(), NotFound(), BadRequest() and Created(). It makes actions easier to unit test than returning HttpResponseMessage directly.
03What is a Web API, and how is it different from an MVC site?Beginner
A Web API returns data (JSON or XML) for other programs — SPAs, mobile apps, other services — instead of HTML pages. In Web API 2 controllers inherit ApiController and actions are selected by HTTP method.
04What are the REST constraints?Beginner
Client–server, statelessness, cacheability, a uniform interface (resources identified by URIs, manipulated through representations), a layered system and optional code-on-demand. Most “REST” APIs follow the first four.
05How does Web API 2 choose an action?Beginner
With convention-based routing (api/{controller}/{id}) it matches the HTTP method to the action name prefix (GetProducts, PostProduct) or to [HttpGet]/[HttpPost] attributes, then matches parameters. Attribute routing with [RoutePrefix] and [Route] is clearer.
06Which status codes should a Web API 2 action return?Beginner
Ok() 200, Created(location, dto) 201, StatusCode(HttpStatusCode.NoContent) 204, BadRequest(ModelState) 400, Unauthorized() 401, NotFound() 404, Conflict() 409 and InternalServerError() 500.
07What is content negotiation?Intermediate
Web API chooses the response format (JSON or XML) based on the Accept header and the registered media-type formatters.
08What are message handlers?Intermediate
DelegatingHandler classes that process every HTTP request and response before routing — used for cross-cutting concerns such as API keys, logging and correlation IDs.
09How do you handle exceptions globally in Web API 2?Intermediate
Implement an ExceptionFilterAttribute for controller exceptions and replace IExceptionHandler and IExceptionLogger services for unhandled exceptions across the pipeline.
10How are parameters bound in Web API 2?Intermediate
Simple types (int, string, DateTime) come from the URI by default; complex types come from the body via a media-type formatter. Use [FromUri] or [FromBody] to override, and only one parameter can be read from the body.
11How do you validate input in Web API 2?Intermediate
Data Annotations on DTOs fill ModelState during binding. Check ModelState.IsValid in the action or register a ValidateModelAttribute action filter globally that returns 400 with the errors.
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext context)
{
if (!context.ModelState.IsValid)
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.ModelState);
}
}
12How do you add dependency injection to Web API 2?Intermediate
Implement or plug in an IDependencyResolver (Unity.WebApi, Autofac.WebApi2, Simple Injector) and assign it to GlobalConfiguration.Configuration.DependencyResolver. Use a per-request scope for DbContext.
13How do you use Entity Framework 6 in an API?Intermediate
A DbContext with DbSet<T> properties, a connection string in Web.config, migrations with Enable-Migrations/Add-Migration/Update-Database, async queries (ToListAsync) and projection to DTOs. Disable lazy loading and proxies for serialisation.
14How do you implement sorting and filtering safely?Intermediate
Accept filter values as parameters, build an IQueryable conditionally and whitelist sort fields with a switch or dictionary mapped to expressions. Never pass a raw column name into SQL.
15How do you document a Web API 2 service?Intermediate
Install Swashbuckle, enable it in SwaggerConfig, turn on XML documentation comments in the project and include them so descriptions appear in Swagger UI at /swagger.
16How does token authentication work with OWIN in Web API 2?Intermediate
The OWIN OAuth authorization server middleware issues bearer tokens from a /token endpoint after validating credentials; the bearer authentication middleware validates them on each request, and [Authorize] protects controllers. JWT middleware is a common alternative.
17How do you enable CORS in Web API 2?Intermediate
Install Microsoft.AspNet.WebApi.Cors, call config.EnableCors() and apply [EnableCors(origins: "https://app.example.com", headers: "*", methods: "*")] to controllers or globally. Do not use "*" origins with credentials.
18How would you migrate a Web API 2 service to ASP.NET Core?Experienced
Move incrementally: create an ASP.NET Core project, port models and services first, replace ApiController with ControllerBase and [ApiController], move configuration from Web.config to appsettings, replace the DI container, and use YARP to route traffic between old and new apps during the transition.
19How do you version a Web API 2 service?Experienced
Use URL segments (api/v1/products), a query string or a header, with the Microsoft.AspNet.WebApi.Versioning package or route prefixes per version. Keep old versions running until clients migrate and document deprecation.
20How do you upload files to a Web API 2 endpoint?Experienced
Check Request.Content.IsMimeMultipartContent(), read with a MultipartFormDataStreamProvider to a temp folder, validate size and type, and move files to permanent storage with server-generated names. Set maxRequestLength and maxAllowedContentLength.
21How do you unit-test Web API 2 controllers?Experienced
Inject fake services, call the action and assert on the IHttpActionResult type (OkNegotiatedContentResult<T>, NotFoundResult, CreatedAtRouteNegotiatedContentResult<T>). Set Request and Configuration when the action builds URLs.
22What improves Web API 2 performance?Experienced
Async actions for I/O, projecting to DTOs with AsNoTracking, output caching headers, compression in IIS, removing the XML formatter if unused, pooling HttpClient, and paging large results.
23How do you deploy a Web API 2 service to Azure App Service?Experienced
Publish from Visual Studio or a pipeline (MSBuild + Web Deploy or a zip deploy), set connection strings and app settings in the portal so they override Web.config, enable Always On and HTTPS Only, and monitor with Application Insights.