0% found this document useful (0 votes)
5 views37 pages

Web API Final PDF

The document provides a comprehensive overview of ASP.NET Web API, including its definition, differences from ASP.NET MVC, and key concepts such as REST principles, HTTP verbs, routing, model binding, authentication, and error handling. It also covers advanced topics like CORS, Swagger integration, and API versioning, along with practical implementation details for various features. Additionally, it discusses best practices for structuring projects, middleware usage, and testing Web APIs.

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)
5 views37 pages

Web API Final PDF

The document provides a comprehensive overview of ASP.NET Web API, including its definition, differences from ASP.NET MVC, and key concepts such as REST principles, HTTP verbs, routing, model binding, authentication, and error handling. It also covers advanced topics like CORS, Swagger integration, and API versioning, along with practical implementation details for various features. Additionally, it discusses best practices for structuring projects, middleware usage, and testing Web APIs.

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/ 37

ASP.

NET Web API – Questions & Answers

1. What is ASP.NET Web API? How is it different from ASP.NET MVC?


Answer:
ASP.NET Web API is a framework for building HTTP services that can be consumed by
various clients (browsers, mobile, IoT).
It uses HTTP verbs like GET, POST, PUT, DELETE and supports RESTful architecture.

ASP.NET MVC ASP.NET Web API


Returns HTML views Returns data (JSON, XML, etc.)
Primarily for web apps Primarily for services/APIs
Uses Controller suffix Uses ApiController or just Controller

2. What is REST and what are its principles?


Answer:
REST (Representational State Transfer) is an architectural style for creating scalable web
services.
Key principles:

 Stateless: No client context stored on the server


 Uniform Interface: Same URL patterns and methods across APIs
 Resource-based: Uses nouns (e.g., /api/products)
 Uses HTTP verbs: GET, POST, PUT, DELETE, PATCH
 Client-Server separation
 Cacheable responses

3. What are HTTP verbs and how are they used in Web API?
Answer:

Verb Purpose Example


GET Read data /api/products
POST Create data /api/products
PUT Update data /api/products/1
DELETE Delete data /api/products/1
PATCH Partial update /api/products/1

Web API maps these verbs to corresponding methods in the controller.


4. How does routing work in ASP.NET Web API?
Answer:
Routing in Web API maps HTTP requests to controller actions using either:

5. What is the difference between [FromBody] and [FromUri] in Web API?


Answer:

 [FromUri]: Extracts data from the query string or route


 [FromBody]: Extracts data from the request body

6. What is IHttpActionResult and why is it used?


Answer:
It’s a return type introduced in Web API 2 to encapsulate HTTP responses.
It improves testability, readability, and customization of responses:Instead of returning raw
HttpResponseMessage, we now use:

 Ok() – 200 OK
 BadRequest() – 400
 NotFound() – 404
 Created() – 201
7. How to enable CORS in ASP.NET Web API?
Answer:
CORS (Cross-Origin Resource Sharing) enables cross-domain requests. Enable it using:

8. What are media types and how does content negotiation work?
Answer:
Content negotiation determines the format (e.g., JSON or XML) of the response based on the
request’s Accept header.

Web API uses formatters like JsonMediaTypeFormatter, XmlMediaTypeFormatter.


9. What is Model Binding in Web API?
Answer:
Model binding maps incoming HTTP request data to method parameters or model objects.

Supports:

 Simple types (int, string) from route/query


 Complex types from body
 Custom binders via IModelBinder

10. How do you secure a Web API?


Answer:
Multiple ways:

 Authentication: Basic Auth, Token-based (JWT), OAuth


 Authorization: Roles, Policies
 HTTPS
 CORS policies
 Use [Authorize] and AllowAnonymous as needed

11. What is Token-based authentication and how do you implement it?


Answer:
Clients send a token (e.g., JWT) in the header instead of credentials:

You generate the token on login, and use middleware like JwtBearerAuthentication to
validate it.

12. How can you return custom HTTP status codes?


Answer:
Or use helpers:

 Ok(), BadRequest(), NotFound(), InternalServerError()

13. How do exception handling and logging work in Web API?


Answer:
Use:

 ExceptionFilterAttribute
 Global handlers via config.Filters.Add(...)
 Custom middleware (in .NET Core Web API)

Logging: use ILogger, NLog, Serilog, or built-in providers.

14. What is throttling in Web API and how do you implement it?
Answer:
Throttling controls the number of API calls from a user/client/IP to avoid overloading.

Use libraries like WebApiThrottle:

15. What is OWIN in Web API?


Answer:
OWIN (Open Web Interface for .NET) decouples the web server from the app.
It allows self-hosting Web API apps and adds middleware flexibility.
16. How do you host Web API?
Answer:

 IIS (standard hosting)


 Self-hosting (using OWIN)
 Azure App Services / Containers
 Kestrel (in .NET Core)

17. What is Swagger/OpenAPI and how do you add it to Web API?


Answer:
Swagger is a tool for documenting and testing APIs.

Add using Swashbuckle:

18. How do you unit test a Web API controller?


Answer:
Use mocking frameworks like Moq + xUnit/NUnit.

Mock dependencies (e.g., services, repositories), call controller methods, and assert responses:

19. How do you handle large file uploads in Web API?


Answer:

 Use MultipartFormDataStreamProvider
 Increase maxRequestLength in config
 Use IFormFile (in .NET Core)
20. How to version APIs in Web API?
Answer:

 Query String: api/products?version=1


 URL Path: api/v1/products
 Header: Accept: application/vnd.myapi.v1+json

Use Microsoft.AspNet.WebApi.Versioning for automated support.

21. What is the difference between ApiController and Controller in Web API?
Answer:

 ApiController is specific to Web API. It:


o Automatically serializes return values to JSON/XML.
o Returns HttpResponseMessage or IHttpActionResult.
o Has built-in support for content negotiation.
 Controller (in MVC) returns views (ViewResult, PartialViewResult) used in web
pages.

22. How do you handle concurrency in Web API?


Answer:
To handle concurrent updates:

 Use Entity Framework's concurrency tokens (like rowversion or timestamp).


 Handle DbUpdateConcurrencyException.
 Implement ETag headers to detect resource changes before updating.

23. How do you send and receive JSON data in Web API?
Answer:

 Set Content-Type: application/json for request.


 Use [FromBody] parameter to receive JSON.
Web API uses JsonMediaTypeFormatter to serialize/deserialize automatically.

24. What are Delegating Handlers?


Answer:
These are message handlers that can process HTTP request and response messages before and
after controller execution.

Use case:

 Logging
 Authentication
 Compression

Register in WebApiConfig.

25. How can you perform dependency injection in Web API?


Answer:
Use built-in .NET Core DI or third-party frameworks like Unity, Autofac, or Ninject in .NET
Framework.

In .NET Core:
Inject in controller:

26. How does authentication and authorization work in Web API?


Answer:

 Authentication verifies the user (e.g., JWT, OAuth, Cookie).


 Authorization determines if the user can access a resource (roles, policies).

Use [Authorize], [AllowAnonymous], or role-based filters:

27. How do you limit JSON response fields in Web API?


Answer:

 Use DTOs/ViewModels with only required fields


 Apply [JsonIgnore] attribute on model properties
 Use Select in LINQ to shape the response

28. How do you create custom filters in Web API?


Answer:
Create a class inheriting from:

 ActionFilterAttribute for action-level


 ExceptionFilterAttribute for global exceptions
 AuthorizationFilterAttribute for custom authorization

Register globally or on actions.

29. What is HttpResponseMessage and how is it used?


Answer:
Represents an HTTP response. Used to control status code, headers, and content explicitly.

In .NET Core, prefer IActionResult or ActionResult<T> instead.

30. What is the difference between ActionResult<T> and IActionResult?


Answer:

 IActionResult: Can return any action result (Ok, NotFound, etc.)


 ActionResult<T>: Combines the return value (T) with possible action results
31. What is the role of HttpClient in Web API?
Answer:
HttpClient is used to consume Web APIs from another .NET app or service.

Use IHttpClientFactory in .NET Core to avoid socket exhaustion.

32. What is media type formatter?


Answer:
A class responsible for serializing and deserializing request/response content.

Examples:

 JsonMediaTypeFormatter
 XmlMediaTypeFormatter
 Custom formatters (e.g., for CSV)

33. How do you configure JSON settings globally in Web API?


Answer:
In Web API (Full Framework):

In .NET Core:
34. How do you return a file from Web API?
Answer:

In classic Web API, return HttpResponseMessage with ByteArrayContent.

35. What is the difference between Post() and Put()?


Answer:

Method Use Case Behavior


POST Create Server assigns ID, adds new
PUT Full update/replace Requires ID, replaces whole resource

36. How to return 404 (Not Found) from Web API?


Answer:

37. What are API contracts and how do you define them?
Answer:
API contracts define expected request and response structure (data shape, status codes).
Defined using:

 Models (DTOs)
 Swagger/OpenAPI spec
 XML comments for documentation
38. How do you test Web API using tools like Postman?
Answer:

 Choose HTTP method (GET/POST/PUT/DELETE)


 Set URL, headers (Content-Type, Authorization)
 Add request body (for POST/PUT)
 Send request and observe response status & body

39. What is ControllerBase vs Controller in .NET Core Web API?


Answer:

 ControllerBase: Used in Web API, does not support views.


 Controller: Inherits ControllerBase, used in MVC, includes View support.

Use ControllerBase for APIs:

40. What is the [ApiController] attribute in ASP.NET Core?


Answer:
Introduced in ASP.NET Core 2.1. It:

 Enables automatic model validation


 Requires attribute routing
 Binds parameters automatically from body, route, query, etc.

41. What is the purpose of [Route] and [HttpGet] in Web API?


Answer:
These are attribute routing annotations used to define:
 [Route]: The custom URI route for the action
 [HttpGet]: Specifies the HTTP verb the action supports

You can also use route templates, constraints, and optional parameters.

42. How do you implement file download functionality in Web API?


Answer:
Return a file stream with appropriate headers:

In classic Web API, use HttpResponseMessage with ByteArrayContent.

43. What is ModelState.IsValid and when is it used?


Answer:
It checks whether the received model object passes validation rules.

 Validation rules are applied using attributes like [Required], [Range], etc.
 With [ApiController], this check is done automatically.

44. How do you configure routing in .NET Core Web API?


Answer:
45. What are action filters, and how do you create one in Web API?
Answer:
Filters allow you to run code before or after controller actions.

Register via [LogActionFilter] or globally in config.

46. How do you implement logging in Web API?


Answer:
Options:

 Use built-in ILogger<T> (in .NET Core)


 Use third-party libraries like Serilog, NLog
 Inject logger into controllers
Then call _logger.LogInformation("Getting product...");

47. What is the [Produces] attribute in Web API?


Answer:
Specifies the media type(s) a controller or action returns.

Used for:

 Content negotiation
 Documentation tools like Swagger

48. What is [Consumes] in Web API?


Answer:
Specifies what content types (MIME) the action accepts:

Useful for validation and content negotiation.

49. What is ApiExplorerSettings in Web API?


Answer:
Helps control which controllers or actions are visible in API documentation tools like Swagger.

Use it to hide internal/private endpoints.


50. How can you return multiple types from a Web API method?
Answer:
Return IActionResult or ActionResult<T> and use conditional logic:

Enables flexibility in returning 200, 404, 400, etc.

51. What is HttpDelete and how is it used?


Answer:
It maps to HTTP DELETE requests:

Used to delete a resource based on ID or other identifier.

52. What is the default response format in Web API?


Answer:

 In Web API (classic): XML (unless overridden)


 In ASP.NET Core: JSON is default using System.Text.Json

The response can be overridden via Accept header or formatters.


53. How do you consume Web API in JavaScript/jQuery?
Answer:
Using fetch or $.ajax:

54. How do you validate model data manually in Web API?


Answer:

Used to check attribute validations like:

 [Required]
 [StringLength]
 [Range]

Also allows custom server-side validations.

55. What is the [Bind] attribute in Web API?


Answer:
Limits the properties that should be bound from the request:

Helps prevent overposting and improves security.


56. What is overposting and how can you prevent it in Web API?
Answer:
Overposting happens when a client sends more properties than expected (e.g., setting admin-
level fields).

Prevention:

 Use ViewModels or DTOs


 Use [Bind] or JsonIgnore
 Avoid binding to entity models directly

57. What is the [NonAction] attribute?


Answer:
Prevents a public method in a controller from being treated as an API action:

58. What is FromForm in Web API?


Answer:
Binds values from an HTTP form (multipart/form-data):

Useful for file uploads or form-based submissions.

59. How do you implement API Rate Limiting?


Answer:

 Use middleware like AspNetCoreRateLimit


 Or implement custom middleware to track IP/request count

60. How do you structure a large Web API project?


Answer:
Recommended layers:

 Controllers – APIs
 Services – Business logic
 Repositories – Data access
 Models/DTOs – Data contracts
 Filters/Middleware – Cross-cutting logic
 Utilities – Helpers, constants, etc.

Helps with testability, maintainability, and scalability.

61. What is the purpose of ConfigureServices and Configure in ASP.NET Core


Web API?

Answer:

 ConfigureServices: Used to register services, middleware, DI dependencies, etc.


 Configure: Used to define the HTTP request pipeline (middleware like routing,
authorization).
62. What is middleware in ASP.NET Core Web API?

Answer:
Middleware is software that processes HTTP requests/responses in a pipeline.

Each middleware can:

 Modify the request


 Short-circuit the pipeline
 Call the next middleware

Example:

63. How do you handle multiple API versions in ASP.NET Core Web API?

Answer:
Install:

Configure in Startup:

Use attributes:

64. What is the [ProducesResponseType] attribute?

Answer:
Describes the HTTP status codes and response types a method returns. Helps with Swagger
documentation.
65. How to implement global exception handling in Web API (Core)?

Answer:
Use middleware:

Or use UseDeveloperExceptionPage() in Development environment.

66. What is the [ApiController] attribute and its benefits?

Answer:

 Auto model validation (returns 400 for invalid models)


 Implicit [FromBody] for complex types
 Better error responses
67. What is ContentResult vs JsonResult?

Answer:

Type Purpose
ContentResult Returns plain text or HTML
JsonResult Returns data as JSON

68. What are strongly typed configuration settings in ASP.NET Core?

Answer:

Bind config sections from appsettings.json to classes:

Inject using IOptions<MySettings>.


69. What is the [FromServices] attribute in Web API?

Answer:
Injects a service directly into an action method parameter.

Useful for per-method DI instead of constructor injection.

70. How do you use route constraints in Web API?

Answer:

Route constraints restrict the type or format of route parameters.

Common constraints: int, guid, alpha, minlength, maxlength, etc.

71. How can you return a custom error message in Web API?

Answer:
Or return detailed object:

You can also create custom exception classes and use global filters.

72. What is the difference between UseRouting() and UseEndpoints()?

Answer:

Method Purpose
UseRouting() Builds route matching info
UseEndpoints() Executes matched endpoint

Used in this order:

73. What are action result return types in ASP.NET Core Web API?

Answer:

 IActionResult
 ActionResult<T>
 Ok(), BadRequest(), NotFound(), Created(), etc.
 JsonResult, ContentResult, FileResult
Example:

74. What is NoContent() used for?

Answer:

Returns HTTP status 204 No Content.


Used when the operation is successful, but no data needs to be returned.

75. What is the [FromHeader] attribute?

Answer:

Binds data from HTTP request headers.


76. How do you handle circular references in JSON serialization?

Answer:

Use [JsonIgnore] or configure serialization to ignore loops.

77. What is dependency injection lifecycle (Scoped, Transient, Singleton)?

Answer:

Lifetime Description
Transient New instance every time
Scoped One instance per request
Singleton One instance for entire app life

78. What are DTOs and why are they used in Web API?

Answer:

DTO = Data Transfer Object.


Used to:

 Hide sensitive data


 Simplify models for client
 Decouple internal domain models
79. How do you test a Web API controller using xUnit?

Answer:

Mock dependencies using Moq:

Use Assert.IsType<OkObjectResult>(result) to validate response.

80. How to call Web API from another Web API?

Answer:

Use HttpClient:

Use IHttpClientFactory to manage HttpClient efficiently.

81. How do you upload files in ASP.NET Core Web API?

Answer:
Use IFormFile to receive uploaded files:
Set enctype="multipart/form-data" on client side.

82. What is IActionResult vs ActionResult<T>?

Answer:

Type Description
IActionResult Generic interface for HTTP responses
ActionResult<T> Combines type-safe return + IActionResult

83. How do you prevent CSRF attacks in Web API?

Answer:

Web APIs typically use tokens (JWT/OAuth). For cookie-authenticated APIs:

 Use Anti-Forgery tokens ([ValidateAntiForgeryToken])


 Use SameSite cookies
 Validate origin headers manually
84. What is the difference between Request.Query, Request.Form, and
Request.Body?

Answer:

Property Used For


Request.Query Access query parameters in URL
Request.Form Access form fields (multipart/form)
Request.Body Read raw body content (e.g., JSON)

85. How do you return a CSV or Excel file from Web API?

Answer:

For Excel:

86. What is OpenAPI/Swagger and how do you integrate it?

Answer:

Swagger (OpenAPI) auto-generates API documentation and UI.


87. How do you make a controller action accessible anonymously?

Answer:

Ensure controller or app has [Authorize] so that this overrides it.

88. What are named HTTP clients in ASP.NET Core?

Answer:

Used with IHttpClientFactory to configure clients per API:

89. What is the [FromRoute] attribute?

Answer:

Binds a method parameter from route values:


Useful when route parameter names differ from method param names.

90. How do you set custom HTTP status codes in ASP.NET Core Web API?

Answer:

You can also use predefined helpers: Ok(), NotFound(), BadRequest().

91. What is HATEOAS in Web API?

Answer:

HATEOAS = Hypermedia As The Engine Of Application State.


It enriches responses with links to related resources/actions.
92. What are filters in Web API and their types?

Answer:

Filters = Reusable logic around controller/action execution.

Types:

 Authorization filters (IAuthorizationFilter)


 Action filters (IActionFilter)
 Result filters (IResultFilter)
 Exception filters (IExceptionFilter)

Used for logging, error handling, caching, etc.

93. How can you cache Web API responses?

Answer:

Use [ResponseCache]:

Or apply in-memory caching for internal data.

94. What is JWT and how is it used in Web API?

Answer:

JWT = JSON Web Token


Used for stateless authentication.

 Issued by auth server


 Sent in Authorization: Bearer <token> header
 Verified using secret key
Validate using:

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

Answer:

Configure roles in claims when issuing JWT tokens or during login.

96. How to log all requests and responses in ASP.NET Core Web API?

Answer:

Use custom middleware:

Also consider using Serilog or Application Insights.


97. What is AutoMapper and why use it in Web API?

Answer:

AutoMapper simplifies object-to-object mapping:

 Map DTOs ↔ Models


 Reduces boilerplate code

98. How can you secure sensitive configuration values (like API keys)?

Answer:

 Use appsettings.Development.json (never commit to repo)


 Use User Secrets (local dev)
 Use Azure Key Vault, AWS Secrets Manager, or Environment Variables in
production

99. What is the difference between REST and SOAP Web Services?

Answer:

REST SOAP
Uses HTTP verbs (GET, POST) Uses XML over HTTP/SMTP
Lightweight and fast Heavy, strict contract
JSON/XML supported XML only
Stateless, cacheable Stateful, not easily cacheable
100. How can you enable CORS in Web API?

Answer:

Use [EnableCors("AllowAll")] on controllers or globally in middleware.

You might also like