Thursday, December 9, 2021

Web API Interview Questions Part 2

 

How to register exception filter globally?

“It is possible to register exception filter globally using following code-

GlobalConfiguration.Configuration.Filters.Add(new

MyTestCustomerStore.NotImplExceptionFilterAttribute());”

Explain what is REST and RESTFUL?

“REST represents REpresentational State Transfer; it is entirely a new aspect of writing a web app.

RESTFUL: It is term written by applying REST architectural concepts is called RESTful services. It focuses on system resources and how the state of the resource should be transported over HTTP protocol.”

Give me one example of Web API Routing?

“Config.Routes.MapHttpRoute(

name: “”MyRoute,””//route name

routeTemplate: “”api/{controller}/{action}/{id}””,//as you can see “”API”” is at the beginning.

defaults: new { id = RouteParameter.Optional }

);”

How can you restrict access methods to specific HTTP verbs in Web API?

“With the help of Attributes (like HTTP verbs), It is possible to implement access restrictions in Web API.

It is possible to define HTTP verbs as an attribute to restrict access. Example:

[HttpPost]

public void Method1(Class obj)

{

//logic”

How can you pass multiple complex types in Web API?

“Two methods to pass the complex types in Web API –

Using ArrayList and Newtonsoft array”

Write a code for passing ArrayList in Web API?

“ArrayList paramList = new ArrayList();

Category c = new Category { CategoryId = 1, CategoryName =“MobilePhones”};

Product p = new Product { Productcode = 1, Name = “MotoG”, Price = 15500, CategoryID = 1 };

paramList.Add(c);

paramList.Add(p);”

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

“Testing tools for web services for REST APIs include:

Jersey API
CFX
Axis
Restlet”

State differences between MVC and WebAPI

“MVC framework is used for developing applications which have User Interface. For that, views can be used for building a user interface.

WebAPI is used for developing HTTP services. Other apps can also be called the WebAPI methods to fetch that data.”

GlobalConfiguration.Configuration.Filters.Add (new MyTestCustomerStore.NotImplExceptionFilterAttribute());”

Explain method to handle error using HttpError in Web API?

In WEB API HttpError used to throw the error info in the response body. “CreateErrorResponse” method is can also use along with this, which is an extension method defined in “HttpRequestMessageExtension.”

Web API uses which library for JSON serialization?

Web API uses Json.NET library for JSON serialization.

What is Exception handling?

“Exception handling is a technique to handle runtime error in the application code. In multiple ways we can handle the error in ASP.NET Web API, some of them are listed below:

HttpResponseException

HttpError

Exception Filters etc.”

In How many ways we can do Web API Versioning?

“We can do Web API Versioning in the following ways:

URI

Query String Parameter

Custom Header Parameter

Accept Header Parameter

How Web API Routes HTTP request to the Controller ASP.NET MVC?

In ASP.NET Web API, HTTP request maps to the controller. In order to determine which action is to invoke, the Web API framework uses a routing table.

What is Basic HTTP Authentication?

Basic HTTP Authentication is a mechanism, where the user is authenticated through the service in which the client pass username and password in the HTTP Authorization request headers. The credentials are formatted as the string “username:password”, based encoded.

What is the use of Authorize Attribute?

Web API 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.

What is Media-Type Formatter in ASP.NET Web API?

Media-Type formatter is an abstract class from which JsonMediaTypeFormatter (handle JSON format) and XmlMediaTypeFormatter (handle XML format) class derived from. Media-Type formatter are classes responsible for serializing the response data in the format that the client asked for.

What is Content Negotiation in Web API?

“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.”

What is Parameter Binding in ASP.NET Web API?

“When Web API calls a method on a controller, it must set the values for the parameters, this particular process is known as Parameter Binding. By Default, Web API uses the below rules in order to bind the parameter:

FromUri: If the parameter is of “Simple” type, then Web API tries to get the value from the URI. Simple Type includes.Net Primitive type like int, double, etc., DateTime, TimeSpan, GUID, string, any type which can be converted from the string type.

FromBody: If the parameter is of “Complex” type, then Web API will try to bind the values from the message body.”

What is Request Verbs or HTTP Verbs?

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

HTTP Get: Used to get or retrieve the resource or information only.

HTTP Post: Used to create a new resource on the collection of resources.

HTTP Put: Used to update the existing Response

HTTP Delete: Used to Delete an existing resource.”

What are the RESTful Services?

“REST stands for the Representational State Transfer. This term is coined by the Roy Fielding in 2000. RESTful is an Architectural style for creating loosely couple applications over the HTTP. In order to make API to be RESTful, it has to adhere the around 6 constraints that are mentioned below:

Client and Server Separation: Server and Clients are clearly isolated in the RESTful services.

Stateless: REST Architecture is based on the HTTP Protocol and the server response can be cached by the clients, but no client context would be stored on the server.

Uniform Interface: Allows a limited set of operation defined using the HTTP Verbs. For eg: GET, PUT, POST, Delete etc.

Cacheable: RESTful architecture allows the response to be cached or not. Caching improves performance and scalability.

Code-On-Demand

Layered System”

What is the difference between ASP.NET MVC application and ASP.NET Web API application?

ASP.NET MVC is used to create a web application which returns both data as well as View whereas Web API is used to create HTTP based Services which only returns data not view. In an ASP.NET MVC application, requests are mapped to Action Methods whereas in the ASP.NET Web API request is mapped to Action based on the Action Verbs.

How can you return JSON from Web API Service irrespective of the Accept header value?

We can easily return JSON from Web API Service irrespective of the Accept header value by removing the XmlFormatter from the Register() method of WebApiConfig.cs file, which is present inside the App_Start folder. Use the following piece of code to remove XmlFormatter completely. It will always return data in JSON format irrespective of the Accept header value in the client request.

How can we unit test the Web API?

“We can use the Fiddler tool to unit test the Web API. Follow the steps given below and do the setting in the Fiddler tool:

Compose Tab -> Enter Request Headers -> Enter the Request Body and execute.”

What do you understand by Internet Media Types?

“The Internet Media Type is a file identification mechanism on the MIME encoding system. It is also known as the “”MIME type.”” It has become the de facto standard for identifying content on the Internet.

For example, suppose we receive an email from a server with an attachment, then the server embeds the media type of the attachment in the message header. So, the browser can launch the appropriate helper application or plug-in.”

What are some commonly seen HTTP Status Codes?

“Following is the list of some commonly seen HTTP Status Codes:

200 (Request is Ok)
201 (Created)
202 (Accepted)
204 (No Content)
301 (Moved Permanently)
400 (Bad Request)
401 (Unauthorized)
403 (Forbidden)
404 (Not Found)
500 (Internal Server Error)
502 (Bad Gateway)
503 (Service Unavailable) etc.”

What are the different HTTP methods used in Web API?

“Following are the different types of HTTP methods used in Web API. We can use them according to the requirements.

GET: The GET method is used to retrieve the information from the respective server using a given URI.
HEAD: The HEAD method is the same as the GET method, but it is used to transfer the status line and header section.
PUT: The PUT method is used to update values, and it can replace all current resources with the uploaded content.
POST: A POST method is a request, and it is used to send data to the respective server.
DELETE: The DELETE method is used to delete or remove all current resources given by a URI.
OPTIONS: This method is used to describe the communication options for the target resource.
CONNECT: The CONNECT method is used to establish a tunnel to the server identified by a given URI.
TRACE: The TRACE method is used to perform a message loop-back test along the target resource path.”

Who can use or consume Web API?

Any client which supports HTTP verbs such as GET, PUT, DELETE, POST etc., can use or consume Web API. Web API services don’t need any configuration, so it is very easy to consume them by any client. Even portable devices like mobile devices can easily consume them, and it is surely the biggest advantages of this technology.

How many ways are you to do Web API Versioning?

“Following are the several ways to do Web API Versioning:

URI
Query String Parameter
Custom Header Parameter
Accept Header Parameter”

What is Web API Versioning, and why is it used?

Web API Versioning is a technique in which Web API is arranged to cope with the business changes, and the API will not impact the client that is using/consuming the existing API. As we know, multiple clients can consume the Web API at a time, so Web API versioning is necessary and required as the business grows, and business requirement changes with the time.

What do you understand by Exception handling in Web API?

“Exception handling is a technique used to handle runtime error in the application code. There are several ways that we can use to handle the error in ASP.NET Web API. Following is a list of some of them:

HttpResponseException
HttpError
Exception Filters etc.”

How can we handle an error using HttpError in Web API?

In Web API, the HttpError method is used to throw the response body’s error info. Along with this, the “CreateErrorResponse” method can also be used, which is an extension method defined in “HttpRequestMessageExtension.”

How can the Web API route the HTTP request to the Controller ASP.NET MVC?

In ASP.NET Web API, an HTTP request is used to map to the controller. The Web API framework uses a routing table to determine which action is to invoke.

How can you pass an ArrayList in Web API?

“The following example shows the code how we can pass an ArrayList in Web API:

ArrayList paramList = new ArrayList();
Category c = new Category { CategoryId = 1, CategoryName =””MobilePhones””};
Product p = new Product { Productcode = 1, Name = “”MotoG””, Price = 15500, CategoryID = 1 };
paramList.Add(c);
paramList.Add(p); “

What do you understand by basic HTTP Authentication?

Basic HTTP Authentication is a mechanism that is used for user authentication. Here, users are authenticated through the service in which the client passes username and password in the HTTP Authorization request headers. The credentials are formatted as the string “username:password,” based on encoded.

Is it possible to pass multiple complex types in Web API?

“Yes, we can easily pass multiple complex types in Web API by using the following two methods:

Using ArrayList
Using Newtonsoft array”

What is Authorize Attribute? What is its use?

Web API provides a built-in authorization filter known as Authorize Attribute. This filter is used to check whether the user is authenticated or not. If not, the user will see 401 Unauthorized HTTP Status Code.

How can you restrict access methods to specific HTTP verbs in Web API?

“It is very easy to implement access restrictions in Web API with Attributes’ help (like HTTP verbs). We can do it by defining HTTP verbs as an attribute to restrict access.

For example,

[HttpPost]
public void Method1(Class obj)
{ “

What are the several new features that come with ASP.NET Web API 2.0?

“Following are the latest new features of ASP.NET Web API framework v2.0:

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

What do you understand by a Media-Type Formatter in ASP.NET Web API?

“The Media-Type formatter is an abstract class acting as a parent class of JsonMediaTypeFormatter and XmlMediaTypeFormatter. These two classes, JsonMediaTypeFormatter (which is used to handle JSON format) and XmlMediaTypeFormatter (which is used to handle XML format), are derived from the Media-Type formatter.

The Media-Type formatter classes are also responsible for serializing the response data in the client’s format.”

What is Content Negotiation in Web API?

“Content Negotiation is the process of selecting the best representation for a given response from a set of various multiple representations available. Following are the two main headers that are responsible for the Content Negotiation:

Content-Type: The content-type header is used to specify the server about the data; the server will receive from the client.
Accept: Another way for Content Negotiation is to use Accept-Header. It is used to specify the format of data requested by the client from a server.”

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...