Web API Experienced Interview Questions

ASP.NET Web API Experienced Interview Questions and Answers

In this article, I am going to discussed the frequently asked ASP.NET Web API Experienced Interview Questions with Answers. Please read our previous article where we discussed the basic ASP.NET Web API Interview Questions.

Why do we need Web API to develop RESTful services as we can also develop RESTful services using WCF?

Yes, it is absolutely possible to develop RESTful services using WCF (Windows Communication Foundation). But there are few reasons why people are moving from WCF to WEB API for developing restful services. Some of them are as follows.

  1. The Web API increases the TDD (Test Driven Development) approach in the development of RESTful services.
  2. If we want to develop RESTful services using WCF, then we need to do a lot of configuration settings, URI templates, contracts & endpoints. WCF basically used to develop SOA (Service Oriented Architecture) based applications.
What are the important return types supported in ASP.NET Web API?

In ASP.NET Web API Application, the controller action methods can return the following:

  1. Void – It simply returns empty content
  2. HttpResponseMessage – It will convert the response message to an HTTP message.
  3. IHttpActionResult – It internally calls the ExecuteAsync method to create an HttpResponseMessage
  4. Other types – You can also write the serialized return value into the response body. For example, you want to return Excel files.
Which .NET framework supports Web API?

The .NET Framework 4.0 and above version supports ASP.NET Web API.

Which protocol ASP.NET Web API supports?

The ASP.NET Web App supports the one and only HTTP protocol.

ASP.NET Web API uses which open-source library for JSON serialization?

The ASP.NET Web API Framework uses the Json.NET library for JSON serialization.

By default, Web API sends an HTTP response with which status code for an uncaught exception?

It will send the response with HTTP Status 500 – Internal Server Error

How do you construct HtmlResponseMessage in ASP.NET Web API?
public class HomeController : ApiController
{
    public HttpResponseMessage Get()
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
        response.Content = new StringContent("Testing", Encoding.Unicode);
        response.Headers.CacheControl = new CacheControlHeaderValue()
        {
            MaxAge = TimeSpan.FromMinutes(20)
        };
        return response;
    }
}
What is Routing in ASP.NET Web API?

The ASP.NET Web API Routing module is responsible for mapping the incoming HTTP requests to a particular controller action method. Based on the incoming requests the Web API uses URI and HTTP verbs to select the action method. Please read our Routing in ASP.NET Web API article for more detail.

How the Web API Framework handle an incoming HTTP Request?

When the ASP.NET Web API Framework receives an HTTP request, it tries to match the URI against one of the route templates available in the routing table. If no route template matches the URI, then Web API Framework returns a 404 error to the client who actually makes the request. Once a matching route is found in the Route Table, the Web API Framework then selects the controller and the action to be executed.

What is SOAP?

SOAP stands for Simple Object Access Protocol and it is an XML-based protocol. SOAP has specifications for both stateless and state-full implementation. It is also an XML-based messaging protocol for exchanging information among computers. The SOAP message consists of an envelope that includes SOAP headers and body to store the actual information we want to send. It supports different types of protocols such as HTTP, TCP, etc.

How Can we assign an alias name for ASP.NET Web API Action?

We can give alias name for Web API action using the “ActionName” attribute as follows: 

[HttpPost]
[ActionName("StudentAdd")]
public void AddStudents(Student aStudent)
{
    StudentRepository.AddStudent(aStudent);
}

For more detail about default naming convention and custom action names, please read our Custom Action Name article.

What is Content Negotiation in Web API?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. One of the standards of the REST service is that the client should have the ability to decide in which format they want the response – whether they want the response in XML or JSON etc. This is called Content Negotiation in Web API. Web API Content Negotiation means the client and server can negotiate. Always It is not possible to return data in the requested format by the Server. That’s why it is called negotiation, not demand. In such cases, the Web API Server will return the data in the default format. Please read our Web API Content Negotiation article where we discussed this concept in detail with examples.

What is CORS?

Before understanding CORS, first, we need to understand the same-origin policy. Browsers allow a web page to make AJAX requests only within the same domain. The Browsers does not allow a web page from making AJAX requests to another domain. This is called the same-origin policy.

CORS is a W3C standard that allows us to get away from the same-origin policy adopted by the browsers that restrict access from making AJAX requests from one domain to another domain. You can enable CORS for your Web API using the respective Web API package (depending on the version of Web API in use). Please read our Cross-Origin Resource Sharing (CORS) in Web API article where we discussed this concept in detail with examples.

What is Web API Attribute Routing?

The ASP.NET Web API 2 supports a new type of routing called attribute routing. Attribute routing means attributes are used to define routes. The Attribute routing provides more control over the URIs by defining routes directly on the actions and controllers. Please read our Attribute Routing in Web API article where we discussed this concept in detail with examples.

Why do we need Attribute Routing in Web API?

The convention-based routing makes it hard to support certain URI patterns that are common in RESTful APIs. For example, resources often contain child resources such as Customers have orders, movies have actors, books have authors, etc. It’s natural to create URIs that reflect these relations.

What is Authentication and Authorization in Web API?

Once you create a Web API Service, then the most important thing that you need to take care of is security means you need to control access to your Web API Services.

Authentication is the process of identifying the user. For example, one user let’s say James logs in with his username and password, and the server uses his username and password to authenticate James.

Authorization is the process of deciding whether the authenticated user is allowed to perform an action on a specific resource (Web API Resource) or not. For example, James (who is an authenticated user) has the permission to get a resource but does not have the permission to create a resource. Please read our Authentication and Authorization in ASP.NET Web API article where we discussed this concept in detail with examples.

What is an HTTP Message handler in ASP.NET Web API Application?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. An HTTP Message Handler in Web API is a class that receives an HTTP request and returns an HTTP response. The Message Handler is derived from the abstract HttpMessageHandler class. The HTTP Message handlers are good for cross-cutting concerns (such as authentication and authorization) that operate at the level of HTTP messages rather than controller actions. For example, a Custom HTTP Message handler might do the following things in a Web API Application.

  1. Read or modify the HTTP request headers.
  2. Add a response header to the HTTP response.
  3. Validate the requests before they reach the controller (i.e., Authentication and Authorization).

Please read our HTTP Message Handler in the Web API article where we discussed this concept in detail with multiple real-time examples.

Why Web API versioning is required?

Once you develop and deploy a Web API service then different clients start consuming your Web API services. As you know, day by day, the business grows, and once the business grows, then the requirement may change, and once the requirement changes, then you may need to change the services as well, but the important thing you need to keep in mind is that you need to do the changes to the services in such a way that it should not break any existing client applications who are already consuming your services.

This is the ideal scenario when the Web API versioning plays an important role. You need to keep the existing services as it is so that the existing client applications will not break, they worked as it is, and you need to develop a new version of the Web API service which will start consuming by the new client applications. Please read our Web API Versioning article where we discussed this concept in detail with examples.

What are the Different options available in Web API to maintain the versioning?

The different options that are available to maintain versioning are as follows.

  1. URI’s
  2. Query String
  3. Version Header
  4. Accept Header
  5. Media Type
What are Request Verbs or HTTP Verbs?

In RESTful service, we can perform all types of CRUD (Create, Read, Update, Delete) Operations. In REST architecture, it is suggested to have a specific Request Verb or HTTP verb on the specific type of call made to the server. Popular Request Verbs or HTTP Verbs are mentioned below:

  1. HTTP GET: This HTTP verb is Used to get the resource only.
  2. HTTP POST: This HTTP verb is Used to create a new resource.
  3. HTTP PUT: This HTTP verb is Used to update an existing resource.
  4. HTTP PATCH: This HTTP verb is Used to update an existing resource.
  5. HTTP DELETE: This HTTP verb is Used to Delete an existing resource.

Note: PUT and PATCH are not similar. If you are updating few columns in your database then use PATCH and if you are updating all the data then use PUT.

What do you mean by Parameter Binding in Web API?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The Parameter Binding means how the Web API Framework binds the incoming HTTP request data to the parameters of an action method of a Web API controller. The ASP.NET Web API action methods can take one or more parameters of different types. An action method parameter can be either a complex type or a primitive type. The Web API Framework binds the action method parameters either with the URL’s query string or from the request body of the incoming HTTP Request based on the parameter type.

By default, if the parameter type is of the primitive type such as int, bool, double, string, GUID, DateTime, decimal, or any other type that can be converted from the string type then Web API Framework sets the action method parameter value from the query string. And if the action method parameter type is a complex type then Web API Framework tries to get the value from the request body.

But we can change this default behavior of the parameter binding process by using [FromBody] and [FromUri] attributes.

  1. FromBody: This will force the Web API Framework to get the value from the request body.
  2. FromUri: This will force the Web API Framework to get the data from the URI (i.e. Route data or Query String)

Please read our Parameter Binding in ASP.NET Web API article where we discussed this concept in detail with examples.

What is the use of Authorize Attribute?

The ASP.NET Web API Framework provided a built-in authorization filter, i.e. Authorize Attribute. This filter checks whether the user is authenticated or not. If not, the user will see 401 Unauthorized HTTP Status Code.

How to Enable CORS in Web API?

If we are going to consume the ASP.NET Web API Service using Jquery Ajax from another domain, then we need to enable CORS in the Web API application. Without enabling CORS, it is not possible to access the service from another domain using AJAX call. Enabling CORS in Web API is a two steps process.

Step1: Install Microsoft.AspNet.WebApi.Cors package.

Step2: Once you installed the Microsoft.AspNet.WebApi.Corspackage then includes the following 2 lines of code in the Register() method of WebApiConfig class which is present inside the App_Start folder of your project.

EnableCorsAttribute cors = new EnableCorsAttribute(“*”, “*”, “*”);
config.EnableCors();

What is Basic HTTP Authentication?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. Basic HTTP Authentication is a mechanism, where the user is authenticated through the service in which the client needs to pass the username and password in the HTTP Authorization request headers. The credentials are formatted as the string “username:password: based encoded. Please read our Basic Authentication in ASP.NET Web API article where we discussed this concept in detail with examples.

What is ASP.Net identity?

ASP.Net identity is the membership management framework given by Microsoft which can be easily integrated with ASP.NET Web API. This helps us in building a secure HTTP service.

What is Token Based Authentication in Web API?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. Nowadays, the use of Web API is increasing in a rapid manner. So as a developer we should know how to develop Web APIs. Only developing Web APIs is not enough if there is no security. So, it also very important to implement security for all types of clients (such as Browsers, Mobile Devices, Desktop applications, and IoTs) who are going to use our Web API services.

The most preferred approach nowadays to secure the Web API resources is by authenticating the users in the Web API server by using the signed token (which contains enough information to identify a particular user) which needs to be sent to the server by the client in each and every request. This is called the Token-Based Authentication approach.

How does the Token-Based Authentication work?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. In order to understand how token-based authentication works, please have a look at the following diagram.

ASP.NET Web API Experienced Interview Questions and Answers

The Token-Based Authentication works as Follows:

  1. The user enters his credentials (i.e. the username and password) into the client (here client means the browser or mobile devices, etc).
  2. The client then sends these credentials (i.e. username and password) to the Authorization Server.
  3. Then the Authorization Server authenticates the client credentials (i.e. username and password) and generates and returns an access token. This Access Token contains enough information to identify a user and also contains the token expiry time.
  4. The client application then includes the Access Token in the Authorization header of the HTTP request to access the restricted resources from the Resource Server until the token is expired.

Please read our Token Based Authentication in Web API article where we discussed this concept in detail with examples.

What is a Refresh Token?

Refresh Token is a special kind of token that can be used to obtain a new renewed access token that allows access to the protected resources. You can request the new access tokens by using the Refresh Token in Web API until the Refresh Token is blacklisted.

Why we need Refresh Token in Web API?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The idea of using the refresh token is to issue a short-lived access token (up to 30 minutes) for the first time and then use the refresh token to obtain a new access token and use that access token to access the protected resources.

So, the user needs to provide the username and password along with the client info (i.e. the client id and client secret) to authenticate himself, and if the information provided by the user is valid, then a response contains a short-lived access token along with a long-lived refresh token gets generated. 

The refresh token is not an access token it is just an identifier for the access token. Now once the access token is expired, the user can use the refresh token to obtain another short-lived access token and so on.

Please read our Refresh Token in the Web API article where we discussed this concept in detail with examples.

What is HMAC Authentication?

This is one of the frequently asked ASP.NET Web API Experienced Interview Questions and Answers. The HMAC stands for Hash-based Message Authentication Code. From the full form of HMAC, we need to understand two things one is Message Authentication Code and the other one is Hash-Based. So HMAC is a mechanism that is used for creating a Message Authentication Code by using a Hash Function.

The most important thing that we need to keep in mind is that while generating the Message Authentication Code using Hash Function we need to use a Shared Secret Key. Moreover, the Shared Secret Key must be shared between the Client and the Server involved in sending and receiving the data. 

Why do we need HMAC Authentication in Web API?

The main uses of HMAC Authentication in Web API are as follows.

  1. Data integrity: It means the data sent by the client to the server has not tampered.
  2. Request origination: The request comes to the server from a trusted client.
  3. Not a replay request: The request is not captured by an intruder and being replayed.

Please read our HMAC in Web API article where we discussed this concept in detail with examples.

In the next article, I am going to discuss SQL Server Interview questions with answers. Here, in this article, I try to explain the most frequently asked ASP.NET Web API Experienced Interview Questions and Answers. I hope you enjoy this ASP.NET Web API Experienced Interview Questions with Answers article. I would like to have your feedback. Please post your feedback, question, or comments about this ASP.NET Web API Experienced Interview Questions with Answers article.

1 thought on “Web API Experienced Interview Questions”

Leave a Reply

Your email address will not be published. Required fields are marked *