Asp.net Web API Interview Q&A With Examples

Questions

  1. What is Web API? What is the purpose of Web API?
  2. What are the advantages of Web API over WCF and web services?
  3. What is REST and RESTful?
  4. Is it possible to use WCF as RESTful services?
  5. What are HTTP verbs or HTTP methods?
  6. How to consume Web API from a .NET MVC application?
  7. What is the difference between Web API and an MVC Controller?
  8. What is Basic Authentication in Web API?
  9. What is API Key Authentication in Web API?
  10. What is Token-based authentication?
  11. What is OAuth?
  12. What is JWT Authentication?
  13. What are the parts of a JWT token?
  14. Where does the JWT token reside in the request?
  15. How to test Web API? What are the tools?
  16. What are the main return types supported in Web API?
  17. What is the difference between HttpResponseMessage and IHttpActionResult?
  18. What is Content Negotiation in Web API?
  19. What is the MediaTypeFormatter class in Web API?
  20. What are the response codes in Web API?
  21. Purpose of the HttpConfiguration class in web API?
  22. Difference between IHttpActionResult and HttpResponseMessage in Web API?
  23. Purpose of the MediaTypeFormatter classs in Web API?
  24. Role of the XMLMediaTypeFormatter class in Web API?
Questions & Answers.

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 or HttpClient.PostAsync() for POST requests.

Example:

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

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:

makefile
Authorization: Basic base64encodedusernameandpassword

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:

makefile
Authorization: ApiKey your_api_key_here

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:

makefile
Authorization: Bearer your_token_here

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:

css
header.payload.signature

14. Where does the JWT token reside in the request?

  • The JWT token is usually passed in the Authorization header of the HTTP request:
makefile
Authorization: Bearer <token>

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 or Startup 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:

csharp
public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); // Formatters (JSON, XML) config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); }

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:
      csharp
      HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("Hello World") }; return response;
  • 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:
      csharp
      public IHttpActionResult Get() { var data = new { Name = "John", Age = 30 }; return Ok(data); // Returns HTTP 200 with the data in JSON format }

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 or application/xml) using the Accept header. The MediaTypeFormatter 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 sends Accept: application/json, the JsonMediaTypeFormatter will be used to serialize the response.

You can also add custom formatters if needed:

csharp
config.Formatters.Add(new MyCustomFormatter());

24. Role of the XmlMediaTypeFormatter class in Web API

  • The XmlMediaTypeFormatter class is a subclass of MediaTypeFormatter 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), the XmlMediaTypeFormatter 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:

    csharp
    public HttpResponseMessage Get() { var data = new { Name = "John", Age = 30 }; return Request.CreateResponse(HttpStatusCode.OK, data, Configuration.Formatters.XmlFormatter); }
  • The XmlMediaTypeFormatter works with the HttpConfiguration to register the correct formatters for the response. By default, Web API uses both JsonMediaTypeFormatter and XmlMediaTypeFormatter, so XML is supported out of the box unless you remove it.

Comments

Popular posts from this blog

SQL Query :- Create Tables,Primary key,Foreign key,Merge Statment

AngularJS

GridView Design Using CSS