Asp.net Web API Interview Q&A With Examples
Questions
- What is Web API? What is the purpose of Web API?
- What are the advantages of Web API over WCF and web services?
- What is REST and RESTful?
- Is it possible to use WCF as RESTful services?
- What are HTTP verbs or HTTP methods?
- How to consume Web API from a .NET MVC application?
- What is the difference between Web API and an MVC Controller?
- What is Basic Authentication in Web API?
- What is API Key Authentication in Web API?
- What is Token-based authentication?
- What is OAuth?
- What is JWT Authentication?
- What are the parts of a JWT token?
- Where does the JWT token reside in the request?
- How to test Web API? What are the tools?
- What are the main return types supported in Web API?
- What is the difference between HttpResponseMessage and IHttpActionResult?
- What is Content Negotiation in Web API?
- What is the MediaTypeFormatter class in Web API?
- What are the response codes in Web API?
- Purpose of the HttpConfiguration class in web API?
- Difference between IHttpActionResult and HttpResponseMessage in Web API?
- Purpose of the MediaTypeFormatter classs in Web API?
- Role of the XMLMediaTypeFormatter class in Web API?
1. What is Web API? What is the purpose of Web API?
- Web API (Application Programming Interface) is a set of protocols and tools for building software applications. It allows different software systems to communicate with each other over HTTP.
- Purpose: Web API is primarily used to build RESTful services that can be consumed by clients (web browsers, mobile devices, etc.) through HTTP. It helps expose business logic or data via the internet, allowing applications to interact in a platform-independent way.
2. What are the advantages of Web API over WCF and web services?
- Lightweight: Web API is designed to be lightweight and can support multiple formats like JSON, XML, and others.
- Ease of use: Web API is easier to use and provides more flexibility compared to WCF and traditional SOAP-based web services.
- Supports HTTP Methods: Web API supports HTTP verbs like GET, POST, PUT, DELETE, making it ideal for RESTful services, while WCF can be overcomplicated for simple services.
3. What is REST and RESTful?
- REST (Representational State Transfer) is an architectural style for designing networked applications. It uses a stateless communication protocol, typically HTTP, and relies on standard operations (GET, POST, PUT, DELETE).
- RESTful refers to web services that adhere to REST principles, providing a lightweight, stateless, and scalable means of communication between systems.
4. Is it possible to use WCF as RESTful services?
- Yes, WCF can be used as RESTful services by configuring it to use HTTP and enabling the appropriate bindings (e.g.,
webHttpBinding
). However, Web API is often preferred for RESTful services because it's simpler and more suited for web-based communication.
5. What are HTTP verbs or HTTP methods?
- HTTP verbs define the actions to be performed on resources in RESTful services. Common HTTP methods include:
- GET: Retrieve data from the server.
- POST: Send data to the server.
- PUT: Update data on the server.
- DELETE: Remove data from the server.
- PATCH: Partially update data on the server.
6. How to consume Web API from a .NET MVC application?
To consume a Web API in a .NET MVC application:
- Create an instance of
HttpClient
. - Use
HttpClient.GetAsync()
for GET requests orHttpClient.PostAsync()
for POST requests.
Example:
7. What is the difference between Web API and an MVC Controller?
- Web API Controller: Specifically designed to handle HTTP requests and return data (usually in JSON or XML).
- MVC Controller: Designed to handle user interactions, process the data, and return views (HTML) for web applications.
Example:
- Web API: Returns data as JSON, e.g.,
return Ok(myData);
- MVC: Returns a view, e.g.,
return View(myData);
8. What is Basic Authentication in Web API?
- Basic Authentication is a simple authentication scheme where the client sends the username and password in the HTTP header. It is usually encoded using Base64.
Example Header:
9. What is API Key Authentication in Web API?
- API Key Authentication involves sending a unique key in the request header or URL, which is used to authenticate the client. It is commonly used for restricting access to specific services or users.
Example Header:
10. What is Token-based authentication?
- Token-based authentication uses tokens (e.g., JWT - JSON Web Token) instead of credentials for authenticating API requests. The token is typically generated after a successful login and is sent in the header of subsequent requests.
Example:
11. What is OAuth?
- OAuth is an authorization framework that allows a third-party application to access a user's data without exposing the user's credentials. It works by issuing tokens that the third party can use to access resources on behalf of the user.
Example:
- A user might log in to a third-party application using their Google credentials via OAuth.
12. What is JWT Authentication?
- JWT (JSON Web Token) is a compact, URL-safe token used for authentication. JWTs contain three parts: header, payload, and signature. They are usually used in token-based authentication systems to secure APIs.
13. What are the parts of a JWT token?
- Header: Contains metadata about the token, like the algorithm used (e.g., HMAC SHA256).
- Payload: Contains the claims, such as the user information.
- Signature: Used to verify the token's authenticity.
Example of JWT:
14. Where does the JWT token reside in the request?
- The JWT token is usually passed in the
Authorization
header of the HTTP request:
15. How to test Web API? What are the tools?
- Tools like Postman, Swagger, or Fiddler are commonly used to test Web APIs. These tools allow you to simulate API requests and analyze the responses.
- Example: Use Postman to send a GET request to your API and view the returned data.
16. What are the main return types supported in Web API?
- IHttpActionResult: A common return type in Web API. It can return various types of responses, including
Ok()
,NotFound()
,BadRequest()
, etc. - HttpResponseMessage: Another return type that represents HTTP responses.
17. What is the difference between HttpResponseMessage and IHttpActionResult?
- HttpResponseMessage: A lower-level object that represents an HTTP response message.
- IHttpActionResult: A higher-level abstraction that returns a response in Web API, and it can be more flexible (e.g.,
Ok()
,NotFound()
).
18. What is Content Negotiation in Web API?
- Content negotiation is the process of selecting the appropriate response format based on the client's request. This can include JSON, XML, etc., depending on the
Accept
header sent by the client.
Example:
- A client may send
Accept: application/json
to receive JSON data.
19. What is the MediaTypeFormatter class in Web API?
- The
MediaTypeFormatter
class is used in Web API to serialize and deserialize content in different formats such as JSON, XML, etc.
20. What are the response codes in Web API?
- 200 OK: The request was successful.
- 201 Created: The request was successful, and a new resource was created.
- 400 Bad Request: The server could not understand the request.
- 401 Unauthorized: Authentication is required or failed.
- 404 Not Found: The requested resource could not be found.
- 500 Internal Server Error: A generic error occurred on the server.
21. Purpose of the HttpConfiguration
class in Web API
- The
HttpConfiguration
class in Web API is used to configure and set up various aspects of the Web API. It defines the behavior of the Web API application, including routing, formatting (media type formatters), message handlers, and other settings. - It is typically used to configure Web API at the global level in the
Global.asax
file orStartup
class (for OWIN-based applications). - Key functions:
- Routing: Defines the URL routing rules for API controllers.
- Formatters: Specifies the formats (JSON, XML, etc.) that the Web API can respond with.
- Filters: Configures global filters (e.g., authentication, authorization).
Example:
22. Difference between IHttpActionResult
and HttpResponseMessage
in Web API
HttpResponseMessage
:- It is a lower-level object that represents an HTTP response message in Web API.
- You manually set properties like status code, headers, and body content.
- It gives more control over the response but is more verbose and less flexible in some scenarios.
- Example:
IHttpActionResult
:- It is a higher-level abstraction that simplifies the process of returning responses.
- Provides methods for returning standard HTTP responses like
Ok()
,NotFound()
,BadRequest()
, etc. - It is more flexible and easier to use because it automatically handles things like status codes and message formatting.
- Example:
Key difference: HttpResponseMessage
gives more control over the response, whereas IHttpActionResult
provides a cleaner, more standardized approach to returning responses.
23. Purpose of the MediaTypeFormatter
class in Web API
- The
MediaTypeFormatter
class is responsible for serializing and deserializing the data to and from different media types such as JSON, XML, etc. It is a core part of Web API's content negotiation mechanism. - When a Web API request is made, the client specifies the expected response format (e.g.,
application/json
orapplication/xml
) using theAccept
header. TheMediaTypeFormatter
class processes the request and response according to the specified format. - Web API uses
MediaTypeFormatter
to convert the response data to the format requested by the client and to parse incoming data from the request body into a usable format.
Example:
- Web API automatically uses the appropriate
MediaTypeFormatter
based on the client's request header. For example, if the client sendsAccept: application/json
, theJsonMediaTypeFormatter
will be used to serialize the response.
You can also add custom formatters if needed:
24. Role of the XmlMediaTypeFormatter
class in Web API
The
XmlMediaTypeFormatter
class is a subclass ofMediaTypeFormatter
that is specifically used for serializing and deserializing XML data.When a client requests XML data (typically by sending
Accept: application/xml
in the request header), theXmlMediaTypeFormatter
is used to format the response or parse the incoming XML request body into an object.Example: If your Web API action method is expecting to return XML:
The
XmlMediaTypeFormatter
works with theHttpConfiguration
to register the correct formatters for the response. By default, Web API uses bothJsonMediaTypeFormatter
andXmlMediaTypeFormatter
, so XML is supported out of the box unless you remove it.
Comments
Post a Comment