Web Api


What is ASP.NET Web API?

The term API stands for Application Programming Interface. ASP.NET Web API is a framework that makes it easy to build Web API’s, i.e. HTTP based services on top of the .NET Framework. ASP.NET Web API is an ideal platform for building Restful services. These services can then be consumed by a broad range of clients like

  1. Browsers
  2. Mobile applications
  3. Desktop applications
  4. IOTs

What are RESTful services?

REST stands for Representational State Transfer. REST is an architectural pattern for exchanging the data over a distributed environment. REST architectural pattern treats each service as a resource and a client can access these resources by using HTTP protocol methods like GET, POST, PUT, and DELETE. 

The REST architectural pattern specifies a Set Of Constraints that a system should adhere to. Here are the REST constraints.

Client-Server constraint –

This is the first constraint. This constraint specifies that a Client sends a request to the server and the server sends a response back to the client. This separation of concerns supports the independent development of both client-side and server-side logic. That means client application and server application should be developed separately without any dependency on each other. A client should only know resource URIs and that’s all. Severs and clients may also be replaced and developed independently as long as the interface between them is not altered.

Stateless constraint –

The next constraint is the stateless constraint. The stateless constraint specifies that the communication between the client and the server must be stateless between requests. This means that we should not be storing anything on the server related to the client. The request from the client should contain all the necessary information for the server to process that request. This ensures that each request can be treated independently by the server.

Cacheable constraint –

Some data provided by the server like the list of products, or list of departments in a company does not change that often. This constraint says that let the client know how long this data is good for so that the client does not have to come back to the server for that data over and over again.

Uniform Interface constraint –

The uniform interface constraint defines an interface between the client and the server. To understand the uniform interface constraint, we need to understand what a resource is and the HTTP verbs – GET, PUT, POST and DELETE. In the context of a REST API, resources typically represent data entities. The product, Employee, Customer, etc. are all resources. The HTTP verb (GET, PUT, POST, and DELETE) that is sent with each request tells the API what to do with the resource. Each resource is identified by a specific URI (Uniform Resource Identifier).

Layered System- 

REST allows us to use a layered system architecture where we deploy the APIs in server A, and store data on server B and authenticate requests in server C. For example, a client cannot ordinarily tell whether it is connected directly to the server or to an intermediary along the way.

What are the differences between REST and SOAP?

The difference between REST and SOAP is given below:

  1. SOAP stands for Simple Object Access Protocol whereas REST stands for Representational State Transfer.
  2. The SOAP is an XML based protocol whereas REST is not a protocol but it is an architectural pattern i.e. resource-based architecture.                         
  3. SOAP has specifications for both stateless and state-full implementation whereas REST is completely stateless.
  4. SOAP enforces message format as XML whereas REST does not enforce message format as XML or JSON.
  5. The SOAP message consists of an envelope which includes SOAP headers and body to store the actual information we want to send whereas REST uses the HTTP build-in headers (with a variety of media-types) to store the information and uses the HTTP GET, POST, PUT and DELETE  methods to perform CRUD operations.
  6. SOAP uses interfaces and named operations to expose the service whereas to expose resources (service) REST uses URI and methods like (GET, PUT, POST, DELETE).
  7. SOAP Performance is slow as compared to REST.

What are the Differences between WCF and Web API? When to choose one over the other?

WCF
  1. It is a framework used for building or developing service-oriented applications. 
  2. WCF can only be consumed by clients, which can understand XML. WCF supports protocols like – HTTP, TCP, Named Pipes etc.
Web API
  1. It is a framework which helps us to build/develop HTTP services
  2. Web API is an open source platform.
  3. It supports most of the MVC features which keep Web API over WCF.

What are the advantages of using ASP.NET Web API?

Using ASP.NET Web API has a number of advantages, but core advantages are:

  1. It works the way HTTP works using standard HTTP verbs like GET, POST, PUT, DELETE, etc. for all CRUD operations
  2. Complete support for routing
  3. It has the ability to be hosted in IIS as well as self-host outside of IIS
  4. Supports Model binding and Validation
  5. OData
  6. Filters
  7. Content Negotiation:-Response generated in JSON or XML format using MediaTypeFormatter

What are the differences between ASP.NET MVC and ASP.NET Web API?

There are following differences between ASP.NET MVC and WEB API:
  1. MVC is used to create web applications that return both views and data but ASP.NET WEB API is used to create rest full HTTP services with the easy and simple way that returns only data, not view.
  2. WEB API helps to build REST-full services over the .NET Framework and it also supports content-negotiation which is not in MVC.
  3. WEB API also takes care of returning data in a particular format like JSON, XML or any other based upon the Accept header in the request. MVC only return data in JSON format using JsonResult.
  4. In WEB API the request is mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.
  5. We can mix WEB API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML or any others format and building a full-blown HTTP service. Typically, this will be called WEB API self-hosting.
  6. Moreover, WEB API is lightweight architecture and except the web application, it can also be used with smartphone apps.

Explain media Formatters in Web API 2

This Web API Interview Questions are asked almost all Web API Interviews.

As we know that web API handles JSON and XML formats based on the Accept and Content-Type header values. But how does web API handles these different formats? The answer is by using Media Type Formatters.

The Media-Type Formatters are classes which are responsible for serializing request/response data so that web API can understand the request data format and send data in the format which client expects.

Technically MediaTypeFormatter is an abstract class from which JsonMediaTypeFormatter and XmlMediaTypeFormatter classes inherit from. JsonMediaTypeFormatter handles JSON and XmlMediaTypeFormatter handles XML.

How to return only JSON from ASP.NET Web API Service irrespective of the Accept header value?

Include the following line in Register() method of WebApiConfig.cs file in App_Start folder. This line of code completely removes XmlFormatter which forces ASP.NET Web API to always return JSON irrespective of the Accept header value in the client request. Use this technique when we want our service to support only JSON and not XML. 

With this change, irrespective of the Accept header value (application/xml or application/json), the Web API service is always going to return JSON.

config.Formatters.Remove(config.Formatters.XmlFormatter);

How to return the only XML from ASP.NET Web API Service irrespective of the Accept header value?

Include the following line in Register() method of WebApiConfig.cs file in App_Start folder. This line of code completely removes JsonFormatter which forces ASP.NET Web API to always return XML irrespective of the Accept header value in the client request. Use this technique when you want your service to support only XML and not JSON.

config.Formatters.Remove(config.Formatters.JsonFormatter);
With this change, irrespective of the Accept header value (application/xml or application/json), the Web API service is always going to return XML.

How to return JSON instead of XML from ASP.NET Web API Service when a request is made from the browser?

So here is what we want the service to do

  1. When a request is issued from the browser, the web API service should return JSON instead of XML. 
  2. When a request is issued from a tool like a fiddler the Accept header value should be respected. This means if the Accept header is set to application/xml the service should return XML and if it is set to application/json the service should return JSON.

There are 2 ways to achieve this

Approach1: 

Include the following line in Register() method of WebApiConfig.cs file in App_Start folder. This tells ASP.NET Web API to use JsonFormatter when a request is made for text/html which is the default for most browsers. The problem with this approach is that the Content-Type header of the response is set to text/html which is misleading.

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“text/html”));

Approach2: 

Include the following class in WebApiConfig.cs file in App_Start folder. 

Register Formatter: 

Place the following line in Register() method of WebApiConfig.cs file in App_Start folder

ASP.NET WEB API Interview Questions and Answers

config.Formatters.Add(new CustomJsonFormatter());
With these 2 changes, when a request is issued from the browser you will get JSON formatted data and the Content-Type header of the response is also set to application/json. If you are using tools like a fiddler and if you set Accept header to application/xml you will still get XML formatted data.

What are main return types supported in Web API?

What is the biggest disadvantage of “Other Return Types” in Web API?

The biggest disadvantage of this approach is that you cannot directly return an error code like 404 error.

How can you handle errors in Web API?

several classes are available in Web API to handle errors. They are HttpError, Exception Filters, HttpResponseException, and Registering Exception Filters.

What New Features comes with ASP.NET Web API 2.0?

  • Attribute Routing
  • Cross-Origin Resource Sharing
  • External Authentication
  • Open Web Interface NET
  • HttpActionResult
  • Web API OData

Name the tools or API for developing or testing web api?

Testing tools for web services for REST APIs include:

  1. Jersey API
  2. CFX
  3. Axis
  4. Restlet

When to choose WCF?

  • Choose WCF if your service needs to support multiple protocols such as HTTP, TCP, Named pipe.
  • Choose WCF if you want to build service with WS-* standards like Reliable Messaging, Transactions, Message Security.
  • Choose WCF if you want to use Request-Reply, One Way, and Duplex message exchange patterns.

When to choose ASP.NET Web API?

  • Choose Web API if you want to build a service that supports only HTTP protocol.
  • Choose Web API to build RESTful HTTP based services.
  • Choose Web API if you are familiar with ASP.NET MVC.

WebAPI default Convention for Binding parameters

  • If the parameter is a simple type like int, bool, double etc., WebAPI tries to get values from the URI (Either from route data or from QueryString).
  • If a parameter is a complex type like customer, product, employee etc., WebAPI tries to get values from request body.

FromURI attribute to instruct Web API to collect or get the value of complex type from the query string.
FromBody attribute instruct Web API to collect or get the value of primitive type from the request body.

What is Content Negotiation in Asp.Net webAPI C#?

Content Negotiation is the process of selecting the best representation for a given response when there are multiple representations available. Two main headers which are responsible for the Content Negotiation are:

  • Content-Type
  • Accept

    The content-type header tells the server about the data, the server is going to receive from the client whereas another way to use Accept-Header, which tells the format of data requested by the Client from a server. In the below example, we requested the data from the server in JSON format.
Web API Routing