0% found this document useful (0 votes)
18 views

Web API

ASP.NET Web API is a framework that helps build HTTP services. It is used for creating simple, non-SOAP based HTTP services and is a lightweight architecture ideal for devices with limited bandwidth. Web API increased the test-driven development approach for RESTful services compared to using WCF.

Uploaded by

R.A. Aruneash
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Web API

ASP.NET Web API is a framework that helps build HTTP services. It is used for creating simple, non-SOAP based HTTP services and is a lightweight architecture ideal for devices with limited bandwidth. Web API increased the test-driven development approach for RESTful services compared to using WCF.

Uploaded by

R.A. Aruneash
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Q.1 What is ASP.NET Web API?

ASP.NET Web API is a framework provided by Microsoft with which we can easily build HTTP
services that can reach a broad of clients, including browsers, mobile, IoT devices, etc. ASP.NET
Web API provides an ideal platform for building RESTful applications on the .NET Framework.

Q.2 What is the difference between ASP.NET Web API


and WCF?
Web API is a Framework to build HTTP Services that can reach a board of clients, including
browsers, mobile, IoT Devices, etc. and provided an ideal platform for building RESTful
applications. It is limited to HTTP based services. ASP.NET framework ships out with the .NET
framework and is Open Source. WCF i.e. Windows Communication Foundation is a framework
used for building Service Oriented applications (SOA) and supports multiple transport protocol
like HTTP, TCP, MSMQ, etc. It supports multiple protocols like HTTP, TCP, Named Pipes,
MSMQ, etc. WCF ships out with the .NET Framework. Both Web API and WCF can be self-
hosted or can be hosted on the IIS Server.

Q.3 When to prefer ASP.NET Web API over WCF?


It totally depends upon the requirement. Choose ASP.NET Web API is you want only HTTP
based services only as Web API is a lightweight architecture and is good for the devices which
have limited bandwidth. We can also create the REST services with the WCF, but that requires
lots of configuration. In case, if you want a service that should support multiple transport
protocol like HTTP, UDP, TCP, etc. then WCF will be a better option.

Q.4 Which .NET Framework supports ASP.NET Web


API?
First Version of ASP.NET Web API is introduced in .NET Framework 4. After that, all the later
versions of the .NET Framework supports the ASP.NET Web API.

Q.5 Can we consume ASP.NET Web API in applications


created using other than .NET?
Yes, we can consume ASP.NET Web API in the applications created using another language
than .NET but that application must have access/supports to the HTTP protocol.

Q.6 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.

Q.7 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

Q.8 What are the new features introduced in ASP.NET


Web API 2.0?
The following features have been introduced in ASP.NET Web API 2.0:

 Attribute Routing
 CORS (Cross-Origin Resource Sharing)
 OWIN (Open Web Interface for .NET) self-hosting
 IHttpActionResult
 Web API OData etc.

Q.9 Can we return View from Web API?


No, Web API does not return View but they return the data. APIController is meant for returning
the data. So, if you need to return a view from the controller class, then make sure to use or
inherit the Controller class.

Q.10 Does ASP.NET Web API replace the WCF?


No, ASP.NET Web API didn’t replace WCF Service as it is only used for creating RESTful
Service i.e. non-SOAP based service.

Q.11 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:

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


2. HTTP Post: Used to create a new resource on the collection of
resources.
3. HTTP Put: Used to update the existing Response
4. HTTP Delete: Used to Delete an existing resource.

Q.12 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.

Q.13 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.

Q. 14 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.

Q.15 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.

1) What is Web API?

WebAPI is a framework which helps you to build/develop HTTP services.


2) Why is Web API required? Is it possible to use RESTful services using
WCF?

Yes, we can still develop RESTful services with WCF. However, there are two
main reasons that prompt users to use Web API instead of RESTful services.

 Web API increases TDD (Test Data Driven) approach in the


development of RESTful services.
 If we want to develop RESTful services in WCF, you surely need a lot of
config settings, URI templates, contracts & endpoints for developing
RESTful services using web API.

3) Why select Web API?

 It is used to create simple, non-SOAP-based HTTP Services


 It is also an easy method for creation with Web API. With WCF REST
Services
 It is based on HTTP and easy to define, expose and consume in a
REST-ful way.
 It is lightweight architecture and ideal for devices that have limited
bandwidth like smartphones.

4) Is it right that ASP.NET Web API has replaced WCF?

It's a not at all true that ASP.NET Web API has replaced WCF. In fact, it is
another way of building non-SOAP based services, i.e., plain XML or JSON
string.

5) What are the advantages of Web API?

Advantages of Web API are:

 OData
 Filters
 Content Negotiation
 Self-Hosting
 Routing
 Model Bindings

6) What are main return types supported in Web API?

A Web API controller action can return following values:

 Void – It will return empty content


 HttpResponseMessage - It will convert the response to an HTTP
message.
 IHttpActionResult - internally calls ExecuteAsync to create an
HttpResponseMessage
 Other types - You can write the serialized return value into the response
body

7) Web API supports which protocol?

Web App supports HTTP protocol.

9) Web API uses which of the following open-source library for JSON
serialization?

Web API uses Json.NET library for JSON serialization.

10) By default, Web API sends HTTP response with which of the
following status code for all uncaught exception?

500 - Internal Server Error

11) 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.
12) How do you construct HtmlResponseMessage?

Following is the way to construct to do so,

public class TestController : 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;

13) What is Web API Routing?

Routing is pattern matching like in MVC.

All routes are registered in Route Tables.


For example:

Routes.MapHttpRoute(

Name: "ExampleWebAPIRoute",

routeTemplate: “api/{controller}/{id}

defaults: new { id = RouteParameter.Optional}

14) What is SOAP?

SOAP is an XML message format used in web service interactions. It allows


to send messages over HTTP or JMS, but other transport protocols can be
used. It is also an XML-based messaging protocol for exchanging information
among computers.

15) What is the benefit of using REST in Web API?

REST is used to make fewer data transfers between client and server which
make it an ideal for using it in mobile apps. Web API also supports HTTP
protocol. Therefore, it reintroduces the traditional way of the HTTP verbs for
communication.

16) How can we use Web API with ASP.NET Web Form?

Web API can be used with ASP.NET Web Form

It can be performed in three simple steps:

1. Create a Web API Controller,


2. Add a routing table to Application_Start method of Global.sax
3. Then you need to make a jQuery AJAX Call to Web API method and get
data.
17) How to you can limit Access to Web API to Specific HTTP Verb?

Attribute programming plays a important role. It is easy to restrict access to an


ASP.NET Web API method to be called using a particular HTTP method.

18) Can you use Web API with ASP.NET Web Form?

Yes, It is possible to use Web API with ASP.Net web form. As it is bundled
with ASP.NET MVC framework. However, it can be used with ASP.NET Web
Form.

19) How Can assign alias name for ASP.NET Web API Action?

We can give alias name for Web API action same as in case of ASP.NET
MVC by using "ActionName" attribute as follows:

[HttpPost]

[ActionName("SaveStudentInfo")]

public void UpdateStudent(Student aStudent)


{
StudentRepository.AddStudent(aStudent);
}

20) What is the meaning of TestApi?

TestApi is a utility library of APIs. Using this library tester developer can create
testing tools and automated tests for a .NET application using data-structure
and algorithms.

21) Explain exception filters?


It will be executed when exceptions are unhandled and thrown from a
controller method. The reason for the exception can be anything. Exception
filters will implement "IExceptionFilter" interface.

22) How can we register exception filter from the action?

We can register exception filter from action using following code:

[NotImplExceptionFilter]

public TestCustomer GetMyTestCustomer(int custid)

//write the code

23) How you can return View from ASP.NET Web API method?

No, we can't return a view from ASP.NET Web API Method. Web API creates
HTTP services that render raw data. However, it's also possible in ASP.NET
MVC application.

24) How to register exception filter globally?

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

GlobalConfiguration.Configuration.Filters.Add(new

MyTestCustomerStore.NotImplExceptionFilterAttribute());
25) 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.

26) 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 }

);

27) 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.

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

The latest features of ASP.NET Web API framework v2.0 are as follows:

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

29) 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

30) 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

31) 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);

32) 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

33) What is REST?

REST is architectural style. It has defined guidelines for creating services


which are scalable. REST used with HTTP protocol using its verbs GET, PUT,
POST and DELETE.

34) How to unit test Web API?

We can perform a Unit test using Web API tools like Fiddler.

Here, are some setting to be done if you are using

Fiddler –Compose Tab -> Enter Request Headers -> Enter the Request Body
and execute

35) How can we restrict access to methods with specific HTTP verbs in
Web API?

Attribute programming is widely used for this functionality. Web API also
allows restricting access of calling methods with the help of specific HTTP
verbs. It is also possible to define HTTP verbs as attribute over method.

36) What is the usage of DelegatingHandler?

DelegatingHandler is used in the Web API to represent Message Handlers


before routing.

37) How can we register exception filter from the action?

We can register exception filter from action using following code

[NotImplExceptionFilter]

public TestCust GetMyTestCust (int custno)

{
//write the code

38) Tell me the code snippet to show how we can return 404 errors from
HttpError?

Code for returning 404 error from HttpError

string message = string.Format(“TestCustomer id = {0} not found”,


customerid);

return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);

39) Explain code snippet to register exception filters from controller?

[NotImplExceptionFilter]

public class TestCustController : Controller

//Your code goes here

40) Web API supports which protocol?

Web App support HTTP protocol

41) Which of the following .NET framework supports Web API?

Web API is supported by NET 4.0 version


42) Web API uses which library for JSON serialization?

Web API uses Json.NET library for JSON serialization.

43) By default, Web API sends HTTP response with which of the
following status code for all uncaught exception?

500 - Internal Server Error

44) 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.”

45) How can we register exception filter globally?

We can register exception filter globally using following code:

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

46) How to handle errors in Web API?

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

47) What is the benefit of WebAPI over WCF?

WCF services use the SOAP protocol while HTTP never use SOAP protocol.
That’s why WebAPI services are lightweight since SOAP is not used. It also
reduces the data which is transferred to resume service. Moreover, it never
needs too much configuration. Therefore, the client can interact with the
service by using the HTTP verbs.

48) 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.

49) Who can consume WebAPI?

WebAPI can be consumed by any client which supports HTTP verbs such as
GET, PUT, DELETE, POST. As WebAPI services don’t need any
configuration, they are very easy to consume by any client. Infract, even
portable devices like Mobile devices can easily consume WebAPI which is
certainly the biggest advantages of this technology.

50) How can we make sure that Web API returns JSON data only?

To make Web API serialize the returning object to JSON format and returns
JSON data only. For that you should add the following code in
WebApiConfig.cs class in any MVC Web API Project:

//JsonFormatter

//MediaTypeHeaderValue

Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new
MediaTypeHeaderValue("application/json"));

//JsonFormatter

//MediaTypeHeaderValue

Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new
MediaTypeHeaderValue("application/json"))
ASP.NET Web API is a framework that makes it easy to build HTTP
services that reach a broad range of clients, including browsers and
mobile devices. ASP.NET Web API is an ideal platform for building
RESTful applications on the .NET Core.

Q1: What is ASP.NET Web API?


Answer
ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients
(including browsers as well as mobile devices) on top of .NET Framework.

Using ASP.NET Web API, we can create non-SOAP based services like plain XML or JSON strings,
etc. with many other advantages including:

 Create resource-oriented services using the full features of HTTP


 Exposing services to a variety of clients easily like browsers or mobile devices, etc.

Q2: What are the Advantages of Using ASP.NET Web API?


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

 It works the HTTP way using standard HTTP verbs like GET, POST, PUT, DELETE, etc. for all
CRUD operations
 Complete support for routing
 Response generated in JSON or XML format using MediaTypeFormatter
 It has the ability to be hosted in IIS as well as self-host outside of IIS
 Supports Model binding and Validation
 Support for OData
Q3: What is the difference between ApiController and Controller?
Answer

 Use Controller to render your normal views.


 ApiController action only returns data that is serialized and sent to the client.

Consider:

public class TweetsController : Controller {


// GET: /Tweets/
[HttpGet]
public ActionResult Index() {
return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
}
}

Or

public class TweetsController : ApiController {


// GET: /Api/Tweets/
public List<Tweet> Get() {
return Twitter.GetTweets();
}
}

Q4:
Which status code used for all uncaught exceptions by
default?
Answer
By default, most exceptions are translated into an HTTP response with status code 500, Internal
Server Error.

Consider:

[Route("CheckId/{id}")]
[HttpGet]
public IHttpActionResult CheckId(int id)
{
if(id > 100)
{
throw new ArgumentOutOfRangeException();
}
return Ok(id);
}
For more control over the response, you can also construct the entire response message and
include it with the HttpResponseException:

public Product GetProduct(int id)


{
Product item = repository.Get(id);
if (item == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No product with ID = {0}",
id)),
ReasonPhrase = "Product ID Not Found"
};
throw new HttpResponseException(resp);
}
return item;
}

Q5: Compare WCF vs ASP.NET Web API?


Answer

 Windows Communication Foundation is designed to exchange standard SOAP-based


messages using variety of transport protocols like HTTP, TCP, NamedPipes or MSMQ, etc.
 On the other hand, ASP.NET API is a framework for building non-SOAP based services over
HTTP only.

Q6: Explain the difference between MVC vs ASP.NET Web API


Answer

 The purpose of Web API framework is to generate HTTP services that reach more clients by
generating data in raw format, for example, plain XML or JSON string. So, ASP.NET Web
API creates simple HTTP services that renders raw data.
 On the other hand, ASP.NET MVC framework is used to develop web applications that
generate Views (HTML) as well as data. ASP.NET MVC facilitates in rendering HTML easy.

Q7: Name types of Action Results in Web API 2


Answer
A Web API controller action can return any of the following:

 void - Return empty 204 (No Content)


 HttpResponseMessage - Return empty 204 (No Content)
 IHttpActionResult - Call ExecuteAsync to create an HttpResponseMessage, then convert to
an HTTP response message
 Some other type - Write the serialized return value into the response body; return 200 (OK).

Q8: What is Attribute Routing in ASP.NET Web API 2.0?


Answer
ASP.NET Web API v2 now support Attribute Routing along with convention-based approach. In
convention-based routes, the route templates are already defined as follows:

Config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{Controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

So, any incoming request is matched against already defined routeTemplate and further routed to
matched controller action. But it’s really hard to support certain URI patterns using conventional
routing approach like nested routes on same controller. For example, authors have
books or customers have orders, students have courses etc.

Such patterns can be defined using attribute routing i.e. adding an attribute to controller action as
follows:

[Route("books/{bookId}/authors")]
public IEnumerable<Author> GetAuthorsByBook(int bookId) { ..... }

ASP.NET Web API is a framework provided by the Microsoft with which we can easily build
HTTP services that can reach a broad of clients, including browsers, mobile, IoT devices, etc.
ASP.NET Web API provides an ideal platform for building RESTful applications on the .NET
Framework.

What is ASP.NET Web API?


ASP.NET Web API is a framework provided by Microsoft with which we can easily build
HTTP services that can reach a broad of clients, including browsers, mobile, IoT devices,
etc. ASP.NET Web API provides an ideal platform for building RESTful applications on
the .NET Framework

What is the difference between ASP.NET Web


API and WCF?
Web API is a Framework to build HTTP Services that can reach a board of clients,
including browsers, mobile, IoT Devices, etc. and provided an ideal platform for building
RESTful applications. It is limited to HTTP based services. ASP.NET framework ships out
with the .NET framework and is Open Source. WCF i.e. Windows Communication
Foundation is a framework used for building Service Oriented applications (SOA) and
supports multiple transport protocol like HTTP, TCP, MSMQ, etc. It supports multiple
protocols like HTTP, TCP, Named Pipes, MSMQ, etc. WCF ships out with the .NET
Framework. Both Web API and WCF can be self-hosted or can be hosted on the IIS
Server.

1. When to prefer ASP.NET Web API over


WCF?
It totally depends upon the requirement. Choose ASP.NET Web API is you want only
HTTP based services only as Web API is a lightweight architecture and is good for the
devices which have limited bandwidth. We can also create the REST services with the
WCF, but that requires lots of configuration. In case, if you want a service that should
support multiple transport protocol like HTTP, UDP, TCP, etc. then WCF will be a better
option.

2. Which .NET Framework supports ASP.NET


Web API?
First Version of ASP.NET Web API is introduced in .NET Framework 4. After that, all the
later versions of the .NET Framework supports the ASP.NET Web API.

3. Can we consume ASP.NET Web API in


applications created using other than .NET?
Yes, we can consume ASP.NET Web API in the applications created using another
language than .NET but that application must have access/supports to the HTTP
protocol.
4. 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.

5. 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:
1. Client and Server Separation: Server and Clients are clearly isolated in the RESTful
services.
2. 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.
3. Uniform Interface: Allows a limited set of operation defined using the HTTP Verbs.
For eg: GET, PUT, POST, Delete etc.
4. Cacheable: RESTful architecture allows the response to be cached or not. Caching
improves performance and scalability.
5. Code-On-Demand
6. Layered System

1. What are the new features introduced in


ASP.NET Web API 2.0?
The following features have been introduced in ASP.NET Web API 2.0:
 Attribute Routing
 CORS (Cross-Origin Resource Sharing)
 OWIN (Open Web Interface for .NET) self-hosting
 IHttpActionResult
 Web API OData etc.

2. Can we return View from Web API?


No, Web API does not return View but they return the data. APIController is meant for
returning the data. So, if you need to return a view from the controller class, then make
sure to use or inherit the Controller class.

3. Does ASP.NET Web API replace the WCF?


No, ASP.NET Web API didn’t replace WCF Service as it is only used for creating RESTful
Service i.e. non-SOAP based service.

4. 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:
1. HTTP Get: Used to get or retrieve the resource or information only.
2. HTTP Post: Used to create a new resource on the collection of resources.
3. HTTP Put: Used to update the existing Response
4. HTTP Delete: Used to Delete an existing resource.

5. What are HTTP Status Codes?


HTTP Status Code Is 3-digit integer in which the first digit of the Status-Code defines
the class of response. Response Header of each API response contains the HTTP Status
Code. HTTP Status Codes are grouped into five categories based upon the first number.
S. No.
HTTP Status Code
Description
1.
1XX
Informational
2.
2XX
Success
3.
3XX
Redirection
4.
4XX
Client-Side Error
5.
5XX
Server-Side Error
Table: HTTP Status Code with Description
Some of the commonly seen HTTP Status Codes are: 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.

6. 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.

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

8. 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.

9. 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.

10. 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.

11. 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.

12. In How many ways we can do Web API


Versioning?
We can do Web API Versioning in the following ways:
1. URI
2. Query String Parameter
3. Custom Header Parameter
4. Accept Header Parameter

13. 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:
1. HttpResponseException
2. HttpError
3. Exception Filters etc.

REST API is extensively considered as the standard protocol for the


web APIs. In one of the largest independent and publicly available
directories for APIs, the ProgrammableWeb, REST API represents
69% of the share of all Internet APIs. Follow along to learn and refresh
26 most advanced REST API Interview Questions and Answers you
may face on your next web developer interview.

Q1: What is REST Web Services?


Answer
REST is the acronym for REpresentational State Transfer. REST is an architectural style for
developing applications that can be accessed over the network. REST architectural style was
brought in light by Roy Fielding in his doctoral thesis in 2000.

REST is a stateless client-server architecture where web services are resources and can be
identified by their URIs. Client applications can use HTTP GET/POST methods to invoke Restful
web services. REST doesn’t specify any specific protocol to use, but in almost all cases it’s used
over HTTP/HTTPS.

When compared to SOAP web services, these are lightweight and doesn’t follow any standard. We
can use XML, JSON, text or any other type of data for request and response.

Q2: Mention some key characteristics of REST?

Answer
Some key characteristics of REST includes

 REST is stateless, therefore the SERVER has no state (or session data)
 With a well-applied REST API, the server could be restarted between two calls as every data
is passed to the server
 Web service mostly uses POST method to make operations, whereas REST uses GET to
access resources

Q3: Mention what is the difference between AJAX and REST?


Answer
Ajax
 In Ajax, the request are sent to the server by using XMLHttpRequest objects. The response is
used by the JavaScript code to dynamically alter the current page
 Ajax is a set of technology; it is a technique of dynamically updating parts of UI without
having to reload the page
 Ajax eliminates the interaction between the customer and server asynchronously

REST

 REST requires the interaction between the customer and server


 REST have a URL structure and a request/response pattern the revolve around the use of
resources
 REST is a type of software architecture and a method for users to request data or
information from servers
 REST requires the interaction between the customer and server

Q4: What are advantages of REST web services?


Answer
Some of the advantages of REST web services are:

 Learning curve is easy since it works on HTTP protocol


 Supports multiple technologies for data transfer such as text, xml, json, image etc.
 No contract defined between server and client, so loosely coupled implementation.
 REST is a lightweight protocol
 REST methods can be tested easily over browser.

Q5: What is a Resource in Restful web services?


Answer
Resource is the fundamental concept of Restful architecture. A resource is an object with:

 a type,
 relationship with other resources and
 methods that operate on it.

Resources are identified with:

 their URI,
 HTTP methods they support and
 request/response data type and format of data.

Q6: What is purpose of a URI in REST based webservices?


Answer
URI stands for Uniform Resource Identifier. Each resource in REST architecture is identified by its
URI. Purpose of an URI is to locate a resource(s) on the server hosting the web service.

A URI is of following format:

<protocol>://<service-name>/<ResourceType>/<ResourceID>

Q7: How does Microservice Architecture work?


Answer

 Clients – Different users from various devices send requests.


 Identity Providers – Authenticates user or clients identities and issues security tokens.
 API Gateway – Handles client requests.
 Static Content – Houses all the content of the system.
 Management – Balances services on nodes and identifies failures.
 Service Discovery – A guide to find the route of communication between microservices.
 Content Delivery Networks – Distributed network of proxy servers and their data centers.
 Remote Service – Enables the remote access information that resides on a network of IT
devices

Q8: Mention what are the HTTP methods supported by REST?


Answer
HTTP methods supported by REST are:

 GET: It requests a resource at the request URL. It should not contain a request body as it will
be discarded. Maybe it can be cached locally or on the server.
 POST: It submits information to the service for processing; it should typically return the
modified or new resource
 PUT: At the request URL it update the resource
 DELETE: At the request URL it removes the resource
 OPTIONS: It indicates which techniques are supported
 HEAD: About the request URL it returns meta information

Q9: Mention what is the difference between PUT and POST?


Answer
PUT puts a file or resource at a particular URI and exactly at that URI. If there is already a file or
resource at that URI, PUT changes that file or resource. If there is no resource or file there, PUT
makes one

POST sends data to a particular URI and expects the resource at that URI to deal with the request.
The web server at this point can decide what to do with the data in the context of specified resource

PUT is idempotent meaning, invoking it any number of times will not have an impact on resources.

However, POST is not idempotent, meaning if you invoke POST multiple times it keeps creating
more resources

Q10: What are disadvantages of REST web services?


Answer
Some of the disadvantages of REST are:

 Since there is no contract defined between service and client, it has to be communicated
through other means such as documentation or emails.
 Since it works on HTTP, there can’t be asynchronous calls.
 Sessions can’t be maintained.
Q11: What are the best practices to create a standard URI for a web
service?
Answer
Following are important points to be considered while designing a URI:

 Use Plural Noun − Use plural noun to define resources. For example, we've used users to
identify users as a resource.

 Avoid using spaces − Use underscore(_) or hyphen(-) when using a long resource name,
for example, use authorized_users instead of authorized%20users.

 Use lowercase letters − Although URI is case-insensitive, it is good practice to keep url in
lower case letters only.

 Maintain Backward Compatibility − As Web Service is a public service, a URI once made
public should always be available. In case, URI gets updated, redirect the older URI to new
URI using HTTP Status code, 300.

 Use HTTP Verb − Always use HTTP Verb like GET, PUT, and DELETE to do the operations
on the resource. It is not good to use operations names in URI.

Q12: What are the best practices to design a resource representation?


Answer
Following are important points to be considered while designing a representation format of a
resource in a RESTful web services −

 Understandability − Both Server and Client should be able to understand and utilize the
representation format of the resource.

 Completeness − Format should be able to represent a resource completely. For example, a


resource can contain another resource. Format should be able to represent simple as well as
complex structures of resources.

 Linkablity − A resource can have a linkage to another resource, a format should be able to
handles such situations.

Q13: What are the disadvantages of statelessness in RESTful


Webservices?
Answer
Following is the disadvantage of statelessness in RESTful web services:

 Web services need to get extra information in each request and then interpret to get the
client's state in case client interactions are to be taken care of.
Q14: What are the primary security issues of web service?
Answer
To ensure reliable transactions and secure confidential information, web services requires very high
level of security which can be only achieved through Entrust Secure Transaction Platform. Security
issues for web services are broadly divided into three sections as described below

1) Confidentiality: A single web service can have multiple applications and their service path
contains a potential weak link at its nodes. Whenever messages or say XML requests are sent by
the client along with the service path to the server, they must be encrypted. Thus, maintaining the
confidentiality of the communication is a must.

2) Authentication: Authentication is basically performed to verify the identity of the users as well as
ensuring that the user using the web service has the right to use or not? Authentication is also done
to track user’s activity. There are several options that can be considered for this purpose

 Application level authentication


 HTTP digest and HTTP basic authentication
 Client certificates

3) Network Security: This is a serious issue which requires tools to filter web service traffic.

Q15: What is addressing in RESTful webservices?


Answer
Addressing refers to locating a resource or multiple resources lying on the server. It is analogous to
locate a postal address of a person.

Q16: What is statelessness in RESTful Webservices?


Answer
As per REST architecture, a RESTful web service should not keep a client state on server. This
restriction is called statelessness. It is responsibility of the client to pass its context to server and
then server can store this context to process client's further request. For example, session
maintained by server is identified by session identifier passed by the client.

Q17: What is the difference between Monolithic, SOA and Microservices


Architecture?
Answer

 Monolithic Architecture is similar to a big container wherein all the software components of
an application are assembled together and tightly packaged.
 A Service-Oriented Architecture is a collection of services which communicate with each
other. The communication can involve either simple data passing or it could involve two or
more services coordinating some activity.
 Microservice Architecture is an architectural style that structures an application as a
collection of small autonomous services, modeled around a business domain.

Q18: What is the purpose of HTTP Status Code?


Answer
HTTP Status code are standard codes and refers to predefined status of task done at server. For
example, HTTP Status 404 states that requested resource is not present on server.

Consider following status codes:

 200 - OK, shows success.


 201 - CREATED, when a resource is successful created using POST or PUT request. Return
link to newly created resource using location header.
 304 - NOT MODIFIED, used to reduce network bandwidth usage in case of conditional GET
requests. Response body should be empty. Headers should have date, location etc.
 400 - BAD REQUEST, states that invalid input is provided e.g. validation error, missing data.
 401 - FORBIDDEN, states that user is not having access to method being used for example,
delete access without admin rights.
 404 - NOT FOUND, states that method is not available.
 409 - CONFLICT, states conflict situation while executing the method for example, adding
duplicate entry.
 500 - INTERNAL SERVER ERROR, states that server has thrown some exception while
executing the method.

Q19: What is the use of Accept and Content-Type Headers in HTTP


Request?
Answer
 Accept headers tells web service what kind of response client is accepting, so if a web
service is capable of sending response in XML and JSON format and client sends Accept
header as application/xml then XML response will be sent. For Accept
header application/json, server will send the JSON response.
 Content-Type header is used to tell server what is the format of data being sent in the
request. If Content-Type header is application/xml then server will try to parse it as XML
data. This header is useful in HTTP Post and Put requests.
Q20: Whether do you find GraphQL the right fit for designing microservice
architecture?

Answer
GraphQL and microservices are a perfect fit, because GraphQL hides the fact that you have a
microservice architecture from the clients. From a backend perspective, you want to split everything
into microservices, but from a frontend perspective, you would like all your data to come from a
single API. Using GraphQL is the best way I know of that lets you do both. It lets you split up your
backend into microservices, while still providing a single API to all your application, and allowing
joins across data from different services.

1. What is REST?
Representational state transfer(REST) is an abstraction of architecture of world wide
web. REST is an architectural style to design networked application.REST makes
communication between remote computers easy by using the simple HTTP protocol which
support for CRUD (Create, Read, Update, and Delete) operations on the server.

2. Name some of the commonly used HTTP methods


used in REST based architecture?
Below are the commonly used HTTP methods used in REST.

o GET − Provides a read only access to a resource.


o PUT − Used to update an existing resource.
o DELETE − Ued to remove a resource.
o POST − Used to create a new resource.
o OPTIONS − Used to get the supported operations on a resource.

3. What is a Resource in REST?


o The service has a base URI that represents whole set of resources

ex: CsharpStar.com/posts

o The base uri can be qualified with an identifier specifying an individual resource

ex: CsharpStar.com/posts/1053

o RESTful services are hierarchical, resources offered by one service can contain
more service
o REST uses various representations to represent a resource where text, JSON, XML.
XML and JSON are the most popular representations of resources

4. Explain REST design principles


There are 5 design principles on REST.

You can read more on this here.


5. Explain different REST Architectural Goals

You can read detailed explanation on each goal here.

6. Which protocol is used by RESTful webservices ?


RESTful web services make use of HTTP protocol as a medium of communication between
client and server.

7. What is messaging in RESTful webservices?


A client sends a message in form of a HTTP Request and server responds in form of a
HTTP Response. This technique is termed as Messaging. These messages contain message
data and metadata i.e. information about message itself.

8. What are the core components of a HTTP Request


and HTTP Response?
There are 5 major components for HTTP Request.
Verb − Indicate HTTP methods such as GET, POST, DELETE, PUT etc.
URI − Uniform Resource Identifier (URI) to identify the resource on server.
HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
Request Header − Contains metadata for the HTTP Request message as key-value pairs.
For example, client ( or browser) type, format supported by client, format of message
body, cache settings etc.
Request Body − Message content or Resource representation.

There are 4 major components for HTTP Response.


Status/Response Code − Indicate Server status for the requested resource. For example
404 means resource not found and 200 means response is ok.
HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
Response Header − Contains metadata for the HTTP Response message as key-value pairs.
For example, content length, content type, response date, server type etc.
Response Body − Response message content or Resource representation.

10. What is URI?


URI stands for Uniform Resource Identifier. Each resource in REST architecture is
identified by its URI.

o Operations on the base URI affect the set of resources as a whole

1. GET lists them


2. POST adds a new resource to the set
3. DELETE deletes the whole set
4. PUT replaces the set with a new set

o Operations on an ID-qualified URI affect an individual resource

1. GET retrieves it
2. DELETE destroys it
3. PUT replaces it or create if doesnot exists

11. What is the purpose of HTTP Verb in REST based


webservices?
VERB identifies the operation to be performed on the resource.
12. What is statelessness in RESTful Webservices?
The communication between client and server must be stateless. This means that each
request from a service consumer should contain all the necessary information for the
service to understand the meaning of the request, and all session state data should then
be returned to the service consumer at the end of each request

13. What are the advantages and disadvantages of


statelessness in RESTful Webservices?
Advantages:
o Web services can treat each method request independently.
o Web services need not to maintain client’s previous interactions. It simplifies
application design.
o As HTTP is itself a statelessness protocol, RESTful Web services work seamlessly
with HTTP protocol

Disadvantages:
o Web services need to get extra information in each request and then interpret to
get the client’s state in case client interactions are to be taken care of.

14. What is the difference between PUT and POST


operations?
PUT − Used to update an existing resource and POST − Used to create a new resource.

15. What should be the purpose of OPTIONS and HEAD


method of RESTful web services?
OPTIONS : list down the supported operations in a web service and should be read only.
HEAD : return only HTTP Header, no Body and should be read only.

16. Explain different state management principles in


REST service?
17. What is caching?
Caching refers to storing server response in client itself so that a client needs not to make
server request for same resource again and again. A server response should have
information about how a caching is to be done so that a client caches response for a
period of time or never caches the server response.

18. What is the purpose of HTTP Status Code?


HTTP Status code are standard codes and refers to predefined status of task done at
server.

HTTP Status Code:

200 – OK, shows success.


201 – CREATED, when a resource is successful created using POST or PUT request. Return
link to newly created resource using location header.
204 – NO CONTENT, when response body is empty
304 – NOT MODIFIED, used to reduce network bandwidth usage in case of conditional GET
requests
400 – BAD REQUEST, states that invalid input is provided
401 – FORBIDDEN, states that user is not having access to method being used
404 – NOT FOUND, states that method is not available
409 – CONFLICT, states conflict situation while executing the method
500 – INTERNAL SERVER ERROR, states that server has thrown some exception while
executing the method
19. Explain the REST Constraints

20. Difference between SOAP and REST services


o REST is simpler to program than SOAP
o Retrieval consists of a URL(GET)
o Creation consists of a URL(POST)
o Update and Delete also simple (PUT,DELETE)
o SOAP semantics are opaque, so it bypasses the features of layered internet
o REST is lightweight on the client side
o you need to write a little bit of script codeand you are off and running
o Javascript frameworks make it browser independent and easy to integrate
o REST is lightweight in server side
o you need to write a little bit of script codeand you are off and running
o Frameworks support the web servers

A Web service is a software system designed to support interoperable machine-to-machine


interaction over a network. It has an interface described in a machine-processable format
(specifically WSDL for SOA). Web services and APIs are two of those overlapping tech terms that
regularly get confused. Follow along to clarify most important interview questions and answers about
SOA, SOAP, REST, RESTful, web services and API.
Q2:
What are different types of Web Services?
Answer
There are two types of web services:

 SOAP Web Services: Runs on SOAP protocol and uses XML technology for sending data.
 Restful Web Services: It’s an architectural style and runs on HTTP/HTTPS protocol almost
all the time. REST is a stateless client-server architecture where web services are resources
and can be identified by their URIs. Client applications can use HTTP GET/POST methods
to invoke Restful web services.

Q4:
What is purpose of a URI in REST based webservices?
Answer
URI stands for Uniform Resource Identifier. Each resource in REST architecture is identified by its
URI. Purpose of an URI is to locate a resource(s) on the server hosting the web service.

A URI is of following format:

<protocol>://<service-name>/<ResourceType>/<ResourceID>

Q5:
Why is the Root Certificate important?
Answer
A Root SSL certificate is a certificate issued by a trusted certificate authority (CA).

In the SSL ecosystem, anyone can generate a signing key and sign a new certificate with that
signature. However, that certificate is not considered valid unless it has been directly or indirectly
signed by a trusted CA.

A trusted certificate authority is an entity that has been entitled to verify that someone is
effectively who it declares to be. In order for this model to work, all the participants on the game
must agree on a set of CA which they trust. All operating systems and most of web browsers ship
with a set of trusted CAs.
Q7:
How would you choose between SOAP and REST web
services?
Answer
Web Services work on client-server model and when it comes to choose between SOAP and REST,
it all depends on project requirements. Let’s look at some of the conditions affecting our choice:

 Do you know your web service clients beforehand? If Yes, then you can define a contract
before implementation and SOAP seems better choice. But if you don’t then REST seems
better choice because you can provide sample request/response and test cases easily for
client applications to use later on.
 How much time you have? For quick implementation REST is the best choice. You can
create web service easily, test it through browser/curl and get ready for your clients. What
kind of data format are supported? If only XML then you can go with SOAP but if you think
about supporting JSON also in future then go with REST.

Q8:
Mention what is the difference between RPC or document
style web services? How you determine to which one to
choose?
Answer
In document style web services, we can transport an XML message as part of SOAP request which
is not possible in RPC style web service. Document style web service is most appropriate in some
application where XML message behaves as document and content of that document can alter and
intention of web service does not rely on the content of XML message

Q9:
What are different ways to test web services?
Answer
 SOAP web services can be tested programmatically by generating client stubs from WSDL
or through software such as Soap UI.

 REST web services can be tested easily with program, curl commands and through browser
extensions. Resources supporting GET method can be tested with browser itself, without any
program.

Q11:
What are main differences between Microservices and
Monolithic Architecture?

Answer
Microservices

 Service Startup is fast


 Microservices are loosely coupled architecture.
 Changes done in a single data model does not affect other Microservices.
 Microservices focuses on products, not projects

Monolithic Architecture

 Service startup takes time


 Monolithic architecture is mostly tightly coupled.
 Any changes in the data model affect the entire database
 Monolithic put emphasize over the whole project

Q17:
What is the difference between encryption, encoding, and
hashing?
Answer
Encryption, encoding and hashing are techniques used for converting the format of data.

 Encryption is used for changing plain text into cipher text so that only authorized entities
can understand it. Encryption deals with keys which are used to encrypt and decrypt the
data. These keys are used to transform a simple text into a cypher text and the vice versa.
 Encoding is used for changing the data into a special format which makes it usable by
external processes. Unlike encryption, the intention of encoding is not related to security.
The message is encoded by using an algorithm or scheme.
 In hashing, the data is converted to a message digest or hash, which is usually a number
generated from a string of text. Hashing is not reversible as encryption and encoding. The
data is converted to a message digest or hash, which is usually a number generated from a
string of text. These digests are important as one can easily match the hash of sent and
received messages to ensure that both are the same and no tempering is done with the
data.

What is ASP.NET Web API and what are its advantages?

ASP.NET Web API is a framework provided by the Microsoft open source technology for building

and consuming HTTP based services on top of .NET Framework. The advantage of Web API is that

it can be consumed by a broader range of clients including web browser and mobile applications, IoT

etc. ASP.NET Web API provides an ideal platform for building RESTful applications on the .NET

Framework. So there will be a client server communication using HTTP protocol.

HTTP (Hypertext Transfer Protocol) is an application level protocol that is used to deliver data such

as html files, image files, query results, etc. on the World Wide Web. HTTP is a stateless protocol,

meaning that after one cycle of request and response the server forgets everything about the cycle,

and it considers another request from the same client as a new request from a new client.

Below is a simple Client-Server architecture of HTTP protocol


Using ASP.NET Web API, we can create non-SOAP based services like plain XML or JSON strings,

etc. with many other advantages including:

 ASP.NET framework ships out with the .NET framework and is Open Source

 Create resource-oriented services using the full features of HTTP.

 Web API is a lightweight architecture and is good for the devices which have limited

bandwidth

 We can expose services to a variety of clients easily like browsers or mobile devices, etc.

 Web API increases TDD (Test Data Driven) approach in the development of RESTful

services.

What are Resources and URIs?

URI is a string of characters used to identify a resource on the internet either by location or by name,

or by both. URI stands for Uniform Resource Identifier.


URI is used to identify resources, for example, in the real world assume there is a person named

“Test Person” who lives in “403, Test City, World”. We can find that person by address or by name or

by both.

URI can be categorized into 2 as URL and URN

 URN: Uniform Resource Name

 URL: Uniform Resource Locator

URI is used to send requests to the server. This can be achieved with the help of both URN and

URL. Using URN is inefficient, as there can be many resources with the same name. So the most

widely used method is URL. URL consists of two required components The Protocol & The Domain.

Look at the following URL:

http://www.testname.net/asp-net-webapi

Here the red colored part is the protocol and the black colored part is the domain, other parts are

optional. It may contain the port/path/query strings/fragments.

What are different HTTP Methods?

There are various types of HTTP methods and they can be used according to the requirements.

These methods are case-sensitive and they must used in uppercase.

 GET – The GET method is used to get or retrieve the information from the respective server

using a given URI.

 HEAD – This is the same as GET, but transfers the status line and header section only.

 PUT – It is used for update and it replaces all current resources with the uploaded content.

 POST – A POST request is used to send data to the respective server.


 DELETE – Deletes or removes all current resources given by a URI.

 OPTIONS – Describes the communication options for the target resource.

 CONNECT – Establishes a tunnel to the server identified by a given URI.

 TRACE – Performs a message loop-back test along the path to the target resource.

Among these methods GET/PUT/POST/DELETE are the most popular methods.

What are HTTP Status Codes?

HTTP Status Codes are the 3 digit integers which contain in server response. There is a meaning for

each number. Response Header of each API response contains the HTTP Status Code. The first

digit of the Status-Code defines the class of response. HTTP Status Codes are grouped into five

categories based upon the first number.

Following are the set of status codes with its meaning:

 1xx: Informational-It means the request has been received and the process is continuing.

 2xx: Success-It means the action was successfully received, understood, and accepted.

 3xx: Redirection-It means further action must be taken in order to complete the request.

 4xx: Client Error-It means the request contains incorrect syntax or cannot be fulfilled

 5xx: Server Error-It means the server failed to fulfill an apparently valid request.

Some of the commonly seen HTTP Status Codes are: 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 is HTTP Content

HTTP header fields are components of the header section of request or response messages in the

Hypertext Transfer Protocol. It defines the operating parameters of an HTTP transaction. There are

more contents in an HTTP header field.

For example, HTTP request to fetch aspnetwebapi.htm page from the web server running on

developmenthelp.net.

What are Internet Media Types?

Media Type is a file identification mechanism on the MIME encoding system, formerly “MIME type”.

The Internet media type has become the de facto standard for identifying content on the Internet.

For example, consider an instance of receiving an email from a server with an attachment, 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 is the difference between WCF Rest and Web API?

It is difficult to say which one is better between Web API and WCF Rest service. Both the

technologies have their own significant in the context of development, hosting and consuming the

service.Although both WCF REST and ASP.NET Web API follow the REST architecture, these have

the following differences:

WCF Rest

 Microsoft has introduced “WebHttpBinding” that needs to be enabled for creating WCF

RESTful Services.
 HTTP Methods are mapped to attributes. So, for each method there must be attributes like –

“WebGet” for GET and “WebInvoke” for POST verbs.

Web API

 Unlike WCF Rest we can use the full features of HTTP in Web API.

 Web API can be hosted in IIS or in applications.

WCF REST ASP.NET Web API

“WebHttpBinding” to be used for creating WCF RestFul services. WebAPI Supports full features of HTTP.

HTTP Methods are mapped to attributes for example It possible to host Web API in IIS as well as
GET for WebGet and POST for WebInvoke. in an application

What is XML & JSON?

XML stands for eXtensible Markup Language. It is a markup language like HTML and is designed to

store and transport data. XML doesn’t do anything, but it can store data in a specific format.

JSON stands for JavaScript Object Notation and is also used to store and transport data. JSON is

often used when data is sent from a server to a web page. JSON is "self-describing" and easy to

understand. JSON is a lightweight format for storing and transporting data.

What are the Advantages of Using ASP.NET Web API?

Using ASP.NET Web API comes with a number of advantages, the core advantages being:
 It works the HTTP way using standard HTTP verbs like GET, POST, PUT, DELETE, etc. for

all CRUD operations


 Routing: Full support for routes/routing

 Response generated in JSON or XML format using MediaTypeFormatter


 Self Hosting: It has the ability to be hosted in IIS as well as self-hosted outside of IIS

 Model Bindings: Supports Model binding and Validation

 Odata: Support for Odata

 Filters

 Content Negotiation

 Link generation to related resources that incorporates routing rules

 Ability to create custom help and test pages using ApiExplorer

Compare WCF vs ASP.NET Web API and state the differences with advantages and
disadvantages?

Windows Communication Foundation is designed to exchange standard SOAP-based messages

using a variety of transport protocols like HTTP, TCP, NamedPipes or MSMQ, etc. WCF i.e.

Windows Communication Foundation is a framework used for building Service Oriented applications

(SOA) and supports multiple transport protocols like HTTP, TCP, MSMQ, etc. WCF ships out with

the .NET Framework. WCF service is good for Message Queue, duplex communication, one-way

messaging. WCF supports SOAP and XML formats.

ASP.NET API is a framework for building non-SOAP based services over HTTP only. Web API is a

Framework to build HTTP Services that can reach a board of clients, including browsers, mobile, IoT

Devices, etc. and provided an ideal platform for building RESTful applications. It is limited to HTTP

based services. ASP.NET framework ships out with the .NET framework and is Open Source. One

major advantage of Web API is that it is the best fit with MVC pattern. Web API supports any media

format including JSON, XML.


 Both Web API and WCF can be self-hosted or can be hosted on the IIS Server.

WCF WebAPI

Multiple protocol support (like HTTP, TCP, Named Pipes and Supports only HTTP
Protocol
more) protocol

Web API supports any


SOAP is the default format. SOAP message
Format media format including
has specific format. Supports SOAP and XML Format
XML and JSON

Light Weight because


Heavy weight because SOAP messages
Size only required
have more than just data
information is passed.

Follows REST
Principles Follows WS-* specification
Principles

Web API is simple and

Configuration Need lot of configuration to run no configuration

needed to run.

While ASP.Net

Web API is perfect for


WCF is good for developing
Service building HTTP
service-oriented applications,
services. Web API is best

fit with MVC pattern.


For each method there must be attributes like Web API supports HTTP protocol verbs
– “WebGet” and “WebInvoke” for communication.

Unlike WCF Rest we can use the full features


For REST service we need to use attribute “WebInvoke”.
of HTTP in Web API

Is it true that ASP.NET Web API has replaced WCF?

It’s a misconception that ASP.NET Web API has replaced WCF. It’s another way of building non-

SOAP based services, for example, plain XML or JSON string etc.

Yes, it has some added advantages like utilizing full features of HTTP and reaching more clients

such as mobile devices etc.

But WCF is still a good choice for the following scenarios:

1. If we intended to use transport other than HTTP e.g. TCP, UDP or Named Pipes.

2. One-way communication or Duplex communication

3. Message Queuing scenario using MSMQ.

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.

Which .NET Framework supports ASP.NET Web API?

First Version of ASP.NET Web API is introduced in .NET Framework 4. After that, all the later
versions of the .NET Framework support the ASP.NET Web API.

What is REST and RestFul?

REST or Representational State Transfer is an architectural style for designing applications. Instead

of using complex mechanisms like CORBA, RPC or SOAP for communication, it dictates that HTTP

should be used.

There are a few principles associated with REST architectural style:

 Everything is a resource i.e. File, Video, Images, WebPage etc.

 Every Resource is identified by a Unique Identifier.

 Be Stateless- Every request should be an independent request.

 Use simple and Uniform Interfaces.


 Everything is done via representation (sending requests from client to server and receiving

responses from server to client).

RESTFUL: It is term written by applying REST architectural concepts and is called RESTful

services. It focuses on system resources and how the state of the resource should be transported

over HTTP protocol.

When to prefer ASP.NET Web API over WCF?

It completely depends upon the requirement. Choose ASP.NET Web API if you want HTTP based
services only, as Web API is a lightweight architecture and is good for the devices which have
limited bandwidth. We can also create the REST services with WCF, but that requires a lot of
configuration. In case you want a service that should support multiple transport protocols like HTTP,
UDP, TCP, etc. then WCF will be the better option.

Explain the difference between WCF vs MVC vs ASP.NET Web API ?

WCF

 It is a framework built for building or developing service-oriented applications.

 It is designed to exchange standard SOAP-based messages

 WCF can be consumed by clients which can understand XML.

 WCF supports a variety of transport protocols like – HTTP, TCP, Named Pipes or MSMQ

etc.

 iWCF ships out with the .NET Framework.

 WCF service is good for Message Queue, duplex communication, one-way messaging.

Web API

 Web API is an open source platform.


 It is a framework which helps us to build/develop HTTP services using HTTP verbs

 It supports most of the MVC features which keep Web API over WCF.

 The purpose of Web API framework is to generate HTTP services that reach more clients by

generating data in raw format, for example, plain XML or JSON string. So, ASP.NET Web

API creates simple HTTP services that render raw data.

 This returns XML or JSON to client.

 All requests are mapped to actions using HTTP verbs.

 We cannot return a view from WebAPI

 In the ASP.NET Web API request is mapped to Action based on the Action Verbs.

MVC

 ASP.NET MVC is used to create a web application which returns both data as well as View

(HTML) whereas Web API is used to create HTTP based Services which only returns data

and not view.

 ASP.NET MVC facilitates in easyrendering of HTML.

 MVC is used to create a web app, in which we can build web pages.

 JSONit will return JSONResult from action method.

 All requests are mapped to the respective action methods.

 We can return a view from MVC

 In an ASP.NET MVC application, requests are mapped to Action Methods.

What are the RESTful Services?

REST stands for Representational State Transfer. This term was coined by Roy Fielding in 2000.

RESTful is an Architectural style for creating loosely coupled applications over HTTP. In order to

make API to be RESTful, it must adhere to the around 6 constraints that are mentioned below:

 Client and Server Separation: Server and Clients are clearly isolated in the RESTful services.
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: 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.

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.

 Uniform Interface: Allows a limited set of operations defined using the HTTP Verbs. For eg:

GET, PUT, POST, Delete etc.

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 verbs

(GET, PUT, POST, and DELETE) that are sent with each request tell the API what to do with the

resource. Each resource is identified by a specific URI (Uniform Resource Identifier).

 Cacheable: RESTful architecture allows the response to be cached or not. Caching improves

performance and scalability.

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 lets the client know how long this data holds good, so that the

client does not have to come back to the server for that data over and over again.
 Code-On-Demand:is any technology that sends executable software code from a server to a

client upon request from the client. The program code lies inactive on a web server until a
client requests a web page that contains a link to the code using the client's web browser.

Upon this request, the web page and the program are transported to the user's machine
using HTTP. When the page is displayed, the code is started in the browser and executes

locally, inside the user's computer until it is stopped (e.g., by the user leaving the web page).
 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.

How to unit test Web API?

We can unit test the Web API using the Fiddler tool. Below are the settings to be done in Fiddler –
Compose Tab -> Enter Request Headers -> Enter the Request Body and execute.

Can we Return View from ASP.NET Web API Method?

Most of the people give the wrong answer for this question. The right answer is No, we can’t. Web
API does not return View but returns the data. As we discussed in an earlier interview question
about the difference between ASP.NET MVC and Web API, ASP.NET Web API creates HTTP
services that render raw data. Although, it’s quite possible in ASP.NET MVC application, the
APIController is meant for returning the data. So, if you need to return a view from the controller
class, then make sure to use or inherit the Controller class.

You might also like