Web API Q&A Part 2
Web API Q&A Part 2
GET
POST
PUT
DELETE
PATCH
OPTIONS, HEAD
csharp
CopyEdit
public IHttpActionResult Get() => Ok(products);
csharp
CopyEdit
config.EnableCors();
[EnableCors("*", "*", "*")]
csharp
CopyEdit
public class GlobalExceptionHandler : ExceptionHandler
13. How can you create a custom route constraint in Web API?
Implement IHttpRouteConstraint to define your own matching logic.
14. What is model binding in Web API?
Maps HTTP request data to action method parameters automatically.
Authorization Filter
Action Filter
Exception Filter
csharp
CopyEdit
var client = new HttpClient();
var response = await client.GetAsync("https://api.example.com/data");
csharp
CopyEdit
return StatusCode(HttpStatusCode.Forbidden);
return ResponseMessage(new HttpResponseMessage(HttpStatusCode.NotFound));
csharp
CopyEdit
public async Task<IHttpActionResult> Upload() {
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
}
HTTPS
Authentication (JWT, OAuth)
Authorization (Roles, Policies)
Throttling
CORS
26. What is Swagger and how do you integrate it with Web API?
Swagger (OpenAPI) is used for API documentation. Use Swashbuckle for integration:
bash
CopyEdit
Install-Package Swashbuckle.AspNetCore
32. How do you return different formats (JSON, XML) from Web API?
Use content negotiation or force the formatter:
csharp
CopyEdit
return Ok(myObj); // auto negotiates
To force XML:
csharp
CopyEdit
return new XmlResult(myObj);
36. What are asynchronous actions and how are they implemented in Web API?
Use async/await for non-blocking operations:
csharp
CopyEdit
public async Task<IHttpActionResult> GetData() {
var data = await _service.GetAsync();
return Ok(data);
}
38. What are the advantages of ASP.NET Core Web API over traditional Web API?
Cross-platform
Built-in DI
Minimal hosting
Performance improvements
Unified pipeline with middleware
39. How do you return custom error responses from Web API?
Return using helper methods:
csharp
CopyEdit
return BadRequest("Invalid data");
return NotFound("Item not found");
42. How can you call one Web API from another?
Use HttpClient in one API to call another:
csharp
CopyEdit
var client = new HttpClient();
var result = await client.GetAsync("https://api.example.com/products");
csharp
CopyEdit
return File(fileBytes, "application/pdf", "document.pdf");
45. How to implement custom authorization in Web API?
Create a custom AuthorizationFilterAttribute and override OnAuthorization() method.
Loose coupling
Easier testing
Centralized configuration
49. How do you return an HTTP 204 (No Content) in Web API?
csharp
CopyEdit
return NoContent();
50. How do you enable HTTPS redirection in ASP.NET Core Web API?
In Program.cs:
csharp
CopyEdit
app.UseHttpsRedirection();
1. Install Swashbuckle.AspNetCore
2. Add in Program.cs:
csharp
CopyEdit
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
csharp
CopyEdit
app.UseSwagger();
app.UseSwaggerUI();
52. How do you bind complex types from query string in Web API?
Use [FromQuery]:
csharp
CopyEdit
public IActionResult Search([FromQuery] SearchModel model)
53. How do you configure global filters in ASP.NET Core Web API?
In Program.cs or Startup.cs:
csharp
CopyEdit
services.AddControllers(options =>
{
options.Filters.Add(typeof(MyCustomFilter));
});
csharp
CopyEdit
[ApiExplorerSettings(IgnoreApi = true)]
csharp
CopyEdit
public IActionResult GetData([FromHeader] string token)
60. How do you handle concurrency in Web API (e.g., PUT/DELETE conflicts)?
61. How can you restrict access to certain IP addresses in Web API?
Use middleware or filters to inspect HttpContext.Connection.RemoteIpAddress and
allow/deny requests.
csharp
CopyEdit
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
68. What are some common response status codes and their meanings?
200 OK – Successful
201 Created – New resource created
400 Bad Request – Invalid input
401 Unauthorized – Auth required
403 Forbidden – Access denied
404 Not Found – Resource missing
500 Internal Server Error – Server issue
csharp
CopyEdit
public IActionResult Get([FromQuery] int page)
70. How do you return a custom object and status code?
csharp
CopyEdit
return StatusCode(418, new { message = "I'm a teapot!" });
71. What are the best practices for designing Web APIs?
73. What is a ControllerBase class and when should you use it?
Base class for API controllers (no view support). Use it for API-only applications.
csharp
CopyEdit
[HttpGet("{id}")]
public IActionResult Get([FromRoute] int id)
76. How do you generate API clients using Swagger/OpenAPI?
Use tools like:
NSwag
AutoRest
OpenAPI Generator
Use UseExceptionHandler()
Or a global exception filter (IExceptionFilter)
79. How can you disable automatic model state validation in [ApiController]?
Override it in Startup.cs or Program.cs:
csharp
CopyEdit
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
80. What are the key differences between REST and SOAP?
csharp
CopyEdit
return Unauthorized("You must be logged in.");
csharp
CopyEdit
[Produces("application/json")]
89. What’s the difference between NoContent() and Ok() in Web API?
91. How can you enforce lowercase URLs in ASP.NET Core Web API?
csharp
CopyEdit
options.LowercaseUrls = true;
92. What is the difference between synchronous and asynchronous controller actions?
94. What are API Keys and how are they used?
API keys are tokens passed via headers or query string to identify and authenticate client
applications.
95. What is the RouteAttribute and how does it differ from HttpGet/HttpPost?
[Route]: Defines the URL pattern
[HttpGet], [HttpPost]: Bind actions to specific HTTP verbs
97. What is middleware in ASP.NET Core and how is it related to Web API?
Middleware processes requests in the pipeline. Common Web API middlewares include:
UseRouting
UseAuthentication
UseAuthorization
UseEndpoints