0% found this document useful (0 votes)
525 views17 pages

GitHub - Devinterview-Io - Asp-Net-Web-Api - ? ASP - Net Web API Coding Interview Questions and Answers For Developers

The document discusses ASP.NET Web API, an open source framework for building HTTP services on .NET. It provides 31 interview questions and answers about ASP.NET Web API. Some key topics covered include what ASP.NET Web API is, status codes, return types, attribute routing, differences between Web API versions, and comparisons to WCF.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
525 views17 pages

GitHub - Devinterview-Io - Asp-Net-Web-Api - ? ASP - Net Web API Coding Interview Questions and Answers For Developers

The document discusses ASP.NET Web API, an open source framework for building HTTP services on .NET. It provides 31 interview questions and answers about ASP.NET Web API. Some key topics covered include what ASP.NET Web API is, status codes, return types, attribute routing, differences between Web API versions, and comparisons to WCF.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 17

21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

Devinterview-io / asp-net-web-api Public

🟣 ASP.NET Web API coding interview questions and answers for developers.

2
stars

0
forks


Star
Notifications

Code Issues Pull requests Actions Projects Wiki Security Insights


main
Go to file

Devinterview-io … on 22 Jan

View code

Top 31 ASP.NET Web API interview


questions
and answers in 2021.
You can check all
31
ASP.NET Web API interview questions here 👉
https://devinterview.io/dev/aspnetWebApi-interview-questions

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

Source: codeproject.com   
https://github.com/Devinterview-io/asp-net-web-api 1/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

🔹 2. Which status code used for all uncaught exceptions


by default?

Answer:
500 – Internal Server Error

Consider:

[Route("CheckId/{id}")]

[HttpGet]

public IHttpActionResult CheckId(int id)

if(id > 100)

throw new ArgumentOutOfRangeException();

return Ok(id);

And the result:

Source: docs.microsoft.com   

🔹 3. Explain the usage of HttpResponseMessage?


Answer:
HttpResponseMessage works with HTTP protocol to return the data with status/error.

Source: c-sharpcorner.com   

🔹 4. What New Features are Introduced in ASP.NET Web


API 2.0?

Answer:

https://github.com/Devinterview-io/asp-net-web-api 2/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

More new features introduced in ASP.NET Web API framework v2.0 are as follows:

Attribute Routing
External Authentication
CORS (Cross-Origin Resource Sharing)
OWIN (Open Web Interface for .NET) Self Hosting
IHttpActionResult

Web API OData

Source: codeproject.com   

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

Source: codeproject.com   

🔹 6. What are main return types supported in Web API?


Answer:
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

https://github.com/Devinterview-io/asp-net-web-api 3/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

Source: career.guru99.com   

🔹 7. What exactly is OAuth (Open Authorization)?


Answer:
OAuth (Open Authorization) is an open standard for access granting/deligation protocol. It
used as a way for Internet users to grant websites or applications access to their information
on other websites but without giving them the passwords. It does not deal with
authentication.

Basically there are three parties involved: oAuth Provider, oAuth Client and Owner.

oAuth Client (Application Which wants to access your credential)


oAuth Provider (eg. facebook, twitter...)
Owner (the person with facebook,twitter.. account )

Source: stackoverflow.com   

🔹 8. What is the difference between ApiController and


Controller?

Answer:
Use Controller to render your normal views.
ApiController action only return 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

https://github.com/Devinterview-io/asp-net-web-api 4/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

public class TweetsController : ApiController {

// GET: /Api/Tweets/

public List<Tweet> Get() {

return Twitter.GetTweets();

Source: stackoverflow.com   

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

Source: codeproject.com   

🔹 10. What are the differences between WebAPI and


WebAPI 2?

Answer:
AttributeRouting
OWIN self host
IHttpActionResult
CORS
HttpRequestContext
Betters Testability
ODATA Improvements
Filter Overrides
ByteRangeStreamContent

Source: stackoverflow.com   

https://github.com/Devinterview-io/asp-net-web-api 5/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

🔹 11. 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) { ..... }

Source: webdevelopmenthelp.net   

🔹 12. 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).
https://github.com/Devinterview-io/asp-net-web-api 6/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

Source: medium.com   

🔹 13. Explain the difference between WCF RESTful Service


vs ASP.NET Web API?

Answer:
Although both WCF REST and ASP.NET Web API follows the REST architecture but these
have follow differences:

WCF REST

Microsoft introduced “WebHttpBinding” to be used for creating WCF RESTful Services.


HTTP Methods are mapped to attributes, for example, “WebGet” for GET method and
“WebInvoke” for POST.

ASP.NET Web API

As compared with WCF REST, Web API supports full features of HTTP.
Its possible to host Web API in IIS as well as in an application.

Source: stackoverflow.com   

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

Source: codeproject.com   

https://github.com/Devinterview-io/asp-net-web-api 7/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

🔹 15. Is it True that ASP.NET Web API has Replaced WCF?


Answer:
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 the full features of HTTP and reaching more clients such as
mobile devices, etc.

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

If we intended to use transport other than HTTP, e.g. TCP, UDP or Named Pipes
Message Queuing scenario using MSMQ
One-way communication or Duplex communication

Source: codeproject.com   

🔹 16. How to Restrict Access to Web API Method to


Specific HTTP Verb?

Answer:
Attribute programming plays its role here. We can easily restrict access to an ASP.NET Web
API method to be called using a specific HTTP method. For example, we may require in a
scenario to restrict access to a Web API method through HTTP POST only as follows:

[HttpPost]

public void UpdateStudent(Student aStudent)

StudentRepository.AddStudent(aStudent);

Source: codeproject.com   

🔹 17. What is Delegating Handler?


Answer:

https://github.com/Devinterview-io/asp-net-web-api 8/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

A message handler is a class that receives an HTTP request and returns an HTTP response.
Message handlers derive from the abstract HttpMessageHandler class.

Typically, a series of message handlers are chained together. The first handler receives an
HTTP request, does some processing, and gives the request to the next handler. At some
point, the response is created and goes back up the chain. This pattern is called a delegating
handler.

Consider:

public class DateObsessedHandler : DelegatingHandler

protected async override Task<HttpResponseMessage> SendAsync(

HttpRequestMessage request,

CancellationToken cancellationToken)

var requestDate = request.Headers.Date;

// do something with the date ...

<span class="token cVar">var</span> response <span class="token cBase">=</span> <span


class="token cVar">await</span> <span class="token cVar">base</span><span class="token
cBase">.</span><span class="token cMod">SendAsync</span><span class="token cBase">
(</span>request<span class="token cBase">,</span> cancellationToken<span class="token
cBase">)</span><span class="token cBase">;</span>

<span class="token cVar">var</span> responseDate <span class="token cBase">=</span>


response<span class="token cBase">.</span>Headers<span class="token cBase">.</span>Date<span
class="token cBase">;</span>

<span class="token cComment">// do something with the date ...</span>

<span class="token cVar">return</span> response<span class="token cBase">;</span>

<span class="token cBase">}</span>

// ...

GlobalConfiguration.Configuration

.MessageHandlers

.Add(new DateObsessedHandler());

Source: docs.microsoft.com   

🔹 19. What's the difference between OpenID and OAuth?


Answer:

https://github.com/Devinterview-io/asp-net-web-api 9/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

OpenID is (mainly) for identification/authentication, so that stackoverflow.com knows


that I own chris.boyle.name (or wherever) and therefore that I am probably the same
person who owned chris.boyle.name yesterday and earned some reputation points.

OAuth is designed for authorization to take actions on your behalf, so that


stackoverflow.com (or wherever) can ask permission to, say, Tweet on your behalf
automatically, without knowing your Twitter password.

Source: stackoverflow.com   

🔹 20. Explain briefly CORS(Cross-Origin Resource


Sharing)?

Answer:
CORS (Cross-origin resource sharing) is a technique that allows restricted resources on a
web page to be requested from another domain outside the domain of which the first
resource was served. A web page may freely attach cross-origin images, scripts, stylesheets,
iframes, and videos. The same-origin security policy by default does not allow certain
“cross-domain” requests, notably Ajax requests.

Cross-origin resource sharing provides a way by which a browser and server can interact to
determine whether allowing the cross-origin requests are safe or not.

Source: webdevelopmenthelp.net   

🔹 21. Can we use Web API with ASP.NET Web Form?


Answer:
Yes, ASP.NET Web API is bundled with ASP.NET MVC framework but still it can be used with
ASP.NET Web Form.
It can be done in three simple steps as follows:

1. Create a Web API Controller


2. Add a routing table to Application_Start method of Global.asax
3. Make a jQuery AJAX Call to Web API method and get data

Source: codeproject.com   

https://github.com/Devinterview-io/asp-net-web-api 10/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

🔹 22. How to Return View from ASP.NET Web API


Method?

Answer:
No, we can't return a view from ASP.NET Web API method. ASP.NET Web API creates HTTP
services that render raw data. Although, it's quite possible in ASP.NET MVC application.

Source: codeproject.com   

🔹 23. How to register exception filter globally?


Answer:
It is possible to register exception filter globally using following code:

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

Source: career.guru99.com   

🔹 24. What is ASP.NET Web API OData?


Answer:
The Open Data Protocol (OData) is a data access protocol created for the web. OData gives
a consistent procedure to query and manipulates data sets via CRUD operations (Create,
Retrieve, Update, and Delete). ASP.NET web API supports each of the v3 and v4 protocol.

ASP.NET Web API 2, support for $expand, $select, and $value options added for OData.
These options simplify to control the representation that is returned from the server.

$expand: Normally, response doesn’t include related entities if we query an OData


collection. By using $expand, we can get related entities inline in response.
$select: It’s used if we wanted to include subset of properites in response instead of all.
$value: It allows to return raw value of the property instead returning in OData format.

Source: webdevelopmenthelp.net   

https://github.com/Devinterview-io/asp-net-web-api 11/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

🔹 25. Explain advantages/disadvantages of using


HttpModule vs DelegatingHandler?

Answer:
HTTP Module - This is an option for Web APIs running on IIS. HTTP modules allow
security code to execute early as part of the IIS pipeline. The principal established from
an HTTP module is available to all components, including the IIS components running
later in the pipeline.

Message Handler - An extensibility option provided by ASP.NET Web API, the greatest
benefit in using a message handler for security is it’s a concept of the ASP.NET Web API
framework and, hence, doesn’t depend on the underlying host or server. Also, a
message handler runs only for Web API requests. The downside of using a message
handler is the lack of finer control.

The DelegatingHandler is part of the Web API pipeline and can run under any host.
HttpModule is not part of Web Api and requires IIS.

Source: stackoverflow.com   

🔹 26. Why should I use IHttpActionResult instead of


HttpResponseMessage?

Answer:
ere are several benefits of IHttpActionResult over HttpResponseMessage mentioned in
Microsoft ASP.Net Documentation:

Simplifies unit testing your controllers.


Moves common logic for creating HTTP responses into separate classes.
Makes the intent of the controller action clearer, by hiding the low-level details of
constructing the response.

Also a class implementing IHttpActionResult as a factory of HttpResponseMessage. With


that mind set, it now becomes an object that need to be returned and a factory that
produces it. In general programming sense, you can create the object yourself in certain
cases and in certain cases, you need a factory to do that.

https://github.com/Devinterview-io/asp-net-web-api 12/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

Long story short - it is not IHttpActionResult versus HttpResponseMessage. Basically, it is


how you want to create the response.

Source: stackoverflow.com   

🔹 27. Explain briefly OWIN (Open Web Interface for .NET)


Self Hosting?

Answer:
OWIN (Open Web Interface for .NET) is an interface for .NET between .NET web
applications and web server. It is an open source technology. OWIN aims to decouple the
connection between ASP.NET applications and IIS by giving a standard interface. Developers
of web servers may be sure that, if they implement OWIN properly, ASP.NET applications
can run on their server. Similarly, new web frameworks can be developed as a replacement
to ASP.NET.

Source: webdevelopmenthelp.net   

🔹 28. What is difference between WCF and Web API and


WCF REST and Web Service?

Answer:
Web Service

It is based on SOAP and return data in XML form.


It support only HTTP protocol.
It is not open source but can be consumed by any client that understands xml.
It can be hosted only on IIS.

WCF

It is also based on SOAP and return data in XML form.


It is the evolution of the web service(ASMX) and support various protocols like TCP,
HTTP, HTTPS, Named Pipes, MSMQ.
The main issue with WCF is, its tedious and extensive configuration.
It is not open source but can be consumed by any client that understands xml.

https://github.com/Devinterview-io/asp-net-web-api 13/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

To use WCF as WCF Rest service you have to enable webHttpBindings.


It support HTTP GET and POST verbs by WebGet and WebInvoke attributes respectively.
To enable other HTTP verbs you have to do some configuration in IIS to accept request
of that particular verb on .svc files
Passing data through parameters using a WebGet needs configuration. The UriTemplate
must be specified.
It support XML, JSON and ATOM data format.

Web API

This is the new framework for building HTTP services with easy and simple way.
Web API is open source an ideal platform for building REST-ful services over the .NET
Framework.
Unlike WCF Rest service, it use the full feature of HTTP (like URIs, request/response
headers, caching, versioning, various content formats)
It also supports the MVC features such as routing, controllers, action results, filter,
model binders, IOC container or dependency injection, unit testing that makes it more
simple and robust.
It can be hosted with in the application or on IIS.
It is light weight architecture and good for devices which have limited bandwidth like
smart phones.
Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or
whatever format you want to add as a MediaTypeFormatter.

Choose between WCF or WEB API

Choose WCF when you want to create a service that should support special scenarios
such as one way messaging, message queues, duplex communication etc.
Choose WCF when you want to create a service that can use fast transport channels
when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you
also want to support HTTP when all other transport channels are unavailable.
Choose Web API when you want

Source: stackoverflow.com   

🔹 29. Could you clarify what is the best practice with Web
API error management?
https://github.com/Devinterview-io/asp-net-web-api 14/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

Answer:
README.md

Web API provides a great deal of flexibility in terms of exception handling:

Use HttpResponseException or the shortcut methods to deal with unhandled


exceptions at the action level.

[Route("CheckId/{id}")]

[HttpGet]

public IHttpActionResult CheckId(int id)

if (id > 100)

var message = new HttpResponseMessage(HttpStatusCode.BadRequest)

Content = new StringContent("We cannot use IDs greater than 100.")

};

throw new HttpResponseException(message);

return Ok(id);

Use Exception Filters to deal with particular unhandled exceptions on multiple actions
and controllers.

[Route("ItemNotFound/{id}")]

[HttpPost]

[ItemNotFoundExceptionFilter] // Exception filter

public IHttpActionResult ItemNotFound(int id)

_service.ThrowItemNotFoundException();

return Ok();

Use ExceptionLogger to log any unhandled exception.

public class UnhandledExceptionLogger : ExceptionLogger

public override void Log(ExceptionLoggerContext context)

var log = context.Exception.ToString();

//Do whatever logging you need to do here.

Use Exception Handlers (one per application) to deal with any unhandled exception
application-wide. They called after Exception Filters and Exception Loggers.

https://github.com/Devinterview-io/asp-net-web-api 15/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

Source: stackoverflow.com   

🔹 30. Explain the difference between WCF, Web API, WCF


REST and Web Service?

Answer:
The .Net framework has a number of technologies that allow you to create HTTP services
such as Web Service, WCF and now Web API. There are a lot of articles over the internet
which may describe to whom you should use.

Web Service

It is based on SOAP and return data in XML form.


It support only HTTP protocol.
It is not open source but can be consumed by any client that understands xml.
It can be hosted only on IIS.

WCF

It is also based on SOAP and return data in XML form.


It is the evolution of the web service(ASMX) and support various protocols like TCP,
HTTP, HTTPS, Named Pipes, MSMQ.
The main issue with WCF is, its tedious and extensive configuration.
It is not open source but can be consumed by any client that understands xml.
It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

To use WCF as WCF Rest service you have to enable webHttpBindings.


It support HTTP GET and POST verbs by WebGet and WebInvoke attributes respectively.
To enable other HTTP verbs you have to do some configuration in IIS to accept request
of that particular verb on .svc files
Passing data through parameters using a WebGet needs configuration. The UriTemplate
must be specified.
It support XML, JSON and ATOM data format.

Web API

This is the new framework for building HTTP services with easy and simple way.

https://github.com/Devinterview-io/asp-net-web-api 16/17
21/09/2021, 12:55 GitHub - Devinterview-io/asp-net-web-api: 🟣 ASP.NET Web API coding interview questions and answers for developers.

Web API is open source an ideal platform for building REST-ful services over the .NET
Framework.
Unlike WCF Rest service, it use the full feature of HTTP (like URIs, request/response
headers, caching, versioning, various content formats)
It also supports the MVC features such as routing, controllers, action results, filter,
model binders, IOC container or dependency injection, unit testing

Source: stackoverflow.com   

🔹 31. How Can We Provide an Alias Name for ASP.NET


Web API Action?
👉🏼 Check
all 31 answers

Thanks 🙌 for reading and good luck on your next tech interview!

Explore 3800+ dev interview question here 👉


Devinterview.io

Releases

No releases published

Packages

No packages published

https://github.com/Devinterview-io/asp-net-web-api 17/17

You might also like