[go: up one dir, main page]

0% found this document useful (0 votes)
3 views16 pages

Web API Q&A Part 2

ASP.NET Web API is a framework for building HTTP-based RESTful services, differing from MVC by focusing on data services and returning JSON/XML instead of HTML views. It supports various HTTP methods, routing mechanisms, and features like content negotiation, model binding, and token-based authentication. Key advantages include lightweight design, ease of use, and the ability to integrate with tools like Swagger for documentation and dependency injection for better testing and maintenance.

Uploaded by

Shrikant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Web API Q&A Part 2

ASP.NET Web API is a framework for building HTTP-based RESTful services, differing from MVC by focusing on data services and returning JSON/XML instead of HTML views. It supports various HTTP methods, routing mechanisms, and features like content negotiation, model binding, and token-based authentication. Key advantages include lightweight design, ease of use, and the ability to integrate with tools like Swagger for documentation and dependency injection for better testing and maintenance.

Uploaded by

Shrikant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

ASP.

NET Web API

1. What is ASP.NET Web API?


A framework for building HTTP-based RESTful services on top of the .NET Framework
or .NET Core.

2. How is Web API different from MVC?

 Web API: Designed for data services, returns JSON/XML


 MVC: Designed for web apps, returns HTML views
Though both use controllers, Web API lacks view-related features.

3. What are the HTTP methods supported in Web API?

 GET
 POST
 PUT
 DELETE
 PATCH
 OPTIONS, HEAD

4. How does routing work in Web API?


Routes are defined using attribute routing ([Route("api/products")]) or convention-based
routing in WebApiConfig.cs.

5. What is attribute routing?


Routing using attributes on controller or action:

6. What is content negotiation?


The process of choosing the correct response format (JSON, XML, etc.) based on the Accept
header of the request.
7. How do you return JSON from a Web API controller?
Just return the object. By default, Web API serializes to JSON if requested via headers.

8. What are MediaTypeFormatters?


They define how Web API serializes and deserializes data (e.g., JsonMediaTypeFormatter,
XmlMediaTypeFormatter).

9. What is IHttpActionResult and how is it used?


Introduced in Web API 2, it provides a cleaner and testable way to return HTTP responses:

csharp
CopyEdit
public IHttpActionResult Get() => Ok(products);

10. What is the difference between IHttpActionResult and HttpResponseMessage?

 IHttpActionResult: High-level, easier to test


 HttpResponseMessage: Low-level, gives more control over the response

11. How do you enable CORS in Web API?


Use the Microsoft.AspNet.WebApi.Cors package and enable it:

csharp
CopyEdit
config.EnableCors();
[EnableCors("*", "*", "*")]

12. How to handle exceptions globally in Web API?


Use ExceptionFilterAttribute or register a global exception handler.

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.

15. What is parameter binding and how does it work?


Web API decides where to bind parameter values from:

 [FromUri] – query string


 [FromBody] – request body

16. What are Filters in Web API?


Used to execute code before or after controller actions:

 Authorization Filter
 Action Filter
 Exception Filter

17. What is token-based authentication in Web API?


Uses bearer tokens (e.g., JWT) for securing APIs instead of cookies/sessions.

18. How do you create a custom message handler?


Derive from DelegatingHandler to intercept HTTP requests/responses for logging, header
manipulation, etc.

19. What is throttling in Web API?


Controlling the number of API requests to prevent abuse using message handlers or middleware.

20. What are the advantages of Web API over WCF?

 RESTful and HTTP native


 Lightweight
 JSON by default
 Easier to consume via browser or mobile
21. What is the use of HttpClient in Web API?
HttpClient is used to consume APIs. It's a high-level class that sends HTTP requests and
receives responses from a URI.

csharp
CopyEdit
var client = new HttpClient();
var response = await client.GetAsync("https://api.example.com/data");

22. What is HttpResponseMessage in Web API?


Represents an entire HTTP response message, including status code, content, and headers.

23. How do you return custom status codes in Web API?


You can return them using HttpResponseMessage or with helper methods:

csharp
CopyEdit
return StatusCode(HttpStatusCode.Forbidden);
return ResponseMessage(new HttpResponseMessage(HttpStatusCode.NotFound));

24. How do you upload a file using Web API?


Use MultipartFormDataStreamProvider to read files from multipart/form-data content.

csharp
CopyEdit
public async Task<IHttpActionResult> Upload() {
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
}

25. How do you secure Web API?

 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

27. How do you implement dependency injection in Web API?


In ASP.NET Core Web API, use services.AddTransient() or AddScoped() in Program.cs.

28. How do you version an API in ASP.NET Web API?


Use URI versioning, header versioning, or query string versioning with
Microsoft.AspNetCore.Mvc.Versioning.

29. How do you create a custom filter in Web API?


Inherit from ActionFilterAttribute, AuthorizationFilterAttribute, or
ExceptionFilterAttribute.

30. What is the use of [ApiController] in .NET Core Web API?

 Automatic model validation


 Implicit [FromBody] and [FromRoute] binding
 Cleaner code

31. What is the [FromRoute], [FromQuery], [FromBody], and [FromForm] attributes?


They tell Web API where to bind data from:

 FromRoute: route parameters


 FromQuery: query string
 FromBody: request body (JSON)
 FromForm: form data (file uploads, etc.)

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);

33. What is ModelState.IsValid in Web API?


Checks if the model passed to an action method meets validation requirements.

34. How do you implement validation in Web API?


Use data annotations like [Required], [Range], etc., and check ModelState.IsValid.

35. What is the role of ApiController base class?


It provides helper methods like Ok(), NotFound(), BadRequest() for consistent responses.

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);
}

37. How do you implement role-based authorization in Web API?


Use [Authorize(Roles = "Admin")] on actions or controllers.

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");

Or build a custom error response object.

40. How do you enable logging in Web API?


Use built-in ILogger<T> in ASP.NET Core, or implement logging middleware / filters in
traditional Web API.

41. What is the difference between [Authorize] and [AllowAnonymous]?

 [Authorize]: Restricts access to authenticated users


 [AllowAnonymous]: Overrides [Authorize], allows public access to a specific
action/controller

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");

43. What is rate limiting in Web API and how is it implemented?


Prevents clients from overusing the API. Use middleware or tools like:

 ASP.NET Core Rate Limiting


 Third-party: AspNetCoreRateLimit, Polly

44. How do you return a file from a Web API?


Use File() helper in .NET Core:

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.

46. What is dependency injection and why is it useful in Web API?


A design pattern that injects dependencies via constructor. Benefits:

 Loose coupling
 Easier testing
 Centralized configuration

47. How to log request and response details in Web API?


Use middleware or custom DelegatingHandler to intercept and log HTTP traffic.

48. What is IActionResult and how does it help in Web API?


An interface that allows flexible return types (e.g., Ok(), BadRequest(), NotFound()), improves
consistency and testability.

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();

51. How do you document APIs using Swagger in ASP.NET Core?

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));
});

54. What is ProblemDetails in ASP.NET Core?


A standardized error response format (RFC 7807) returned by Web API for consistent error
reporting.

55. What is the [ProducesResponseType] attribute used for?


Documents expected HTTP status codes in Swagger and helps clients understand API responses.

56. What is [ApiExplorerSettings]?


Controls API visibility in Swagger:

csharp
CopyEdit
[ApiExplorerSettings(IgnoreApi = true)]

57. How do you bind header values to action parameters?


Use [FromHeader]:

csharp
CopyEdit
public IActionResult GetData([FromHeader] string token)

58. What is the difference between ControllerBase and Controller?

 ControllerBase: Used for APIs (no view support)


 Controller: Includes view support (used in MVC)

59. What is Model Binding vs Model Validation?

 Model Binding: Maps data from request to method parameters


 Model Validation: Checks data against annotations like [Required], [Range], etc.

60. How do you handle concurrency in Web API (e.g., PUT/DELETE conflicts)?

 Use ETags and If-Match headers


 Or implement optimistic concurrency with row versioning in the database

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.

62. What is IActionFilter and how is it different from IAsyncActionFilter?

 IActionFilter: Synchronous filter


 IAsyncActionFilter: Asynchronous filter (recommended for non-blocking logic)

63. How do you perform unit testing in Web API?

 Use xUnit or NUnit


 Mock dependencies using Moq
 Test controllers with TestServer or WebApplicationFactory
64. What is HttpDelete, and can it have a body?
HttpDelete represents a DELETE request. Technically it can have a body, but it's not
recommended or widely supported.

65. How do you implement caching in Web API?

 In-memory caching via IMemoryCache


 Response caching using [ResponseCache]
 Distributed cache using IDistributedCache

66. What is the ApiVersion attribute and how is it used?


Used with API versioning:

csharp
CopyEdit
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]

67. How do you return paginated results in Web API?


Implement logic with pageNumber, pageSize query params and return pagination metadata in
headers or body.

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

69. How do you access query string parameters in Web API?


Use [FromQuery]:

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?

 Use nouns for routes (/products, /users)


 Use proper HTTP methods
 Return standard status codes
 Version your API
 Secure with authentication & authorization

72. What is ActionResult<T> and why is it useful?


Combines return type and response code in a single generic return type (e.g.,
ActionResult<Product>), supports both object and status.

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.

74. What’s the difference between Task<IActionResult> and IActionResult?

 Task<IActionResult>: Async method (recommended for I/O operations)


 IActionResult: Sync method

75. How do you bind route values to method parameters?


Using [FromRoute]:

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

They create strongly-typed clients in C#, TypeScript, etc.

77. What is UseRouting() vs UseEndpoints() in ASP.NET Core?

 UseRouting(): Matches routes


 UseEndpoints(): Executes route handler (controller action)

⚠️UseRouting() should come before UseAuthorization().

78. How can you log exceptions globally?

 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?

Feature REST SOAP


Protocol HTTP XML over HTTP/SMTP/etc.
Format JSON/XML Strictly XML
Lightweight Yes No
Flexibility High Rigid
81. How do you return a 401 Unauthorized from an API manually?

csharp
CopyEdit
return Unauthorized("You must be logged in.");

82. What’s the use of [Produces] attribute in Web API?


Specifies the response content type for Swagger and clients:

csharp
CopyEdit
[Produces("application/json")]

83. What is HATEOAS in REST APIs?


Hypermedia As The Engine Of Application State – Adds navigational links inside responses to
guide client actions.

84. What is a DTO in Web API and why is it used?


DTO (Data Transfer Object) is a lightweight object used to expose only necessary data,
improving security and performance.

85. How do you validate nested objects in Web API?


Use data annotations on nested properties and check ModelState.IsValid.

86. What is the [BindNever] attribute?


Prevents certain model properties from being bound during model binding (e.g., Id, IsAdmin,
etc.).

87. How to ensure an API only allows HTTPS requests?

 Enforce redirection via app.UseHttpsRedirection()


 Use [RequireHttps] filter
 Configure it in reverse proxy/load balancer

88. How do you test Web API endpoints manually?


 Postman
 curl
 Swagger UI
 Fiddler

89. What’s the difference between NoContent() and Ok() in Web API?

 Ok(): Returns HTTP 200 with data


 NoContent(): Returns HTTP 204 without a body (used in updates/deletes)

90. What is the [Consumes] attribute?


Specifies which content types the action can accept

91. How can you enforce lowercase URLs in ASP.NET Core Web API?

csharp
CopyEdit
options.LowercaseUrls = true;

Set this in AddRouting() config.

92. What is the difference between synchronous and asynchronous controller actions?

 Async actions (async Task<IActionResult>) are non-blocking


 Sync actions block threads and can reduce scalability under high load

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


Cross-Origin Resource Sharing allows client apps from different domains to consume the API.
Without it, browser blocks the request.

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

96. How do you cache Web API responses per user?


Use in-memory or distributed caching with cache keys including the user ID or token.

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

98. What is Route Constraints in Web API?


They restrict route values to certain types

99. How can you disable Swagger in Production?


Wrap it in an environment check

100. What are some tools for API load testing?

 Postman (Collection Runner)


 JMeter
 Apache Bench
 k6
 Artillery

You might also like