Top 30 ASP.Net Web API Interview Questions and Answers


In this blog, I have collected interview questions and answers of ASP.Net Web API.
If you are working on Microsoft Technologies especially ASP.Net framework, then you must aware about ASP.Net Web API.

Web API is the Microsoft open source technology for developing REST services based on HTTP protocol. ASP.Net Web API is a framework for building, consuming HTTP based service. The advantage of Web API is that it can be consumed by a wide range of clients like a web browser and mobile applications.

Below are few important ASP.Net Web API interview questions and answers which are helpful in interview preparation.

1. What is ASP.Net Web API?

Web API is the Microsoft open source technology for developing REST services based on HTTP protocol. ASP.Net Web API is a framework for building, consuming HTTP based service. The advantage of Web API is that it can be consumed by a wide range of clients like a web browser and mobile applications. Read more about Web API.

2. Web API vs WCF REST API

It is difficult to say which one is better between Web API and WCF Rest service. This is why because both the technology have their own significance in the context of development, hosting and consuming the service.

WCF service is good for Message Queue, duplex communication, one way messaging.
Web API is good for HTTP based service.

One major advantage of Web API is it is the best fit with MVC pattern.

WCF supports SOAP and XML format, while Web API supports any media format including JSON, XML.

WCF is good for developing service oriented applications, while ASP.Net Web API is perfect for building HTTP services.

WCF supports HTTP, TCP, Named Pipes as protocol on another side Web API supports HTTP protocol only.

WEB API is easy for those developers who are already familiar to MVC pattern.

WCF needs lots of configuration to run, while Web API is simple and no configuration needed to run.

The advantage of Web API over WCF services.

The disadvantage of WCF over Web API is that WCF requires a lot of configuration to work, but in Web API it is simple and no extra configuration.

3. Advantages of using ASP.Net Web API

Advantages of ASP.Net Web API are -

Filters
OData
Routing
Model Binding
Easy with MVC

To know more about the benefits of ASP.Net Web API, View this blog - Benefits of using Web API

4. What are the various return types in ASP.Net Web API?

HttpResponseMessage
IHttpActionResult
void
Other Type - string, int, or other entity types

5. How to create a basic ASP.Net Web API in Visual Studio 2015 or 2017?

To create a Web API you visit my earlier blog - How to create a Web API?

6. What is ASP.Net Web API routing?

Routing in ASP.Net Web API is the process which decides which action and which controller should be called.
There are 2 ways to implement routing in Web API.
1. Convention based routing
2. Attribute based routing - This mechanism was introduced in ASP.Net Web API 2.0

You can visit an earlier blog - Routing in ASP.Net Web API

7. What is Media type formatter in Web API?

MediaTypeFormatter - Base class to handle serializing and deserializing strongly-typed objects.
BefferedMediaTypeFormatter - Represents a helper class to allow asynchronous formatter on top of the asynchronous formatter infrastructure.

Visit this blog for detail explanation - ASP.Net Web API Media Type formatter

8. CORS issue in Web API?

CORS stands for Cross-Origin Resource Sharing. CORS resolve the same-origin restriction for JavaScript. The same Origin means that a JavaScript can only make AJAX call to the web pages within the same origin.

To enable CORS in Web API you must install CORS nuget package using Package Manager Console.
Now open WebAPIConfig.cs file

add config.EnableCors();

Then add EnableCors attribute to the Controller class and define the origin

[EnableCors(origins: "<origin url>", headers: "*", methods: "*")]


9. How to secure an ASP.Net Web API?

Web API security means, you want to control your Web API and decide who can access the API and who can't access the Web API.

Your Web API can be accessed by anyone who knows the URL. This is not a good practice in the context of security.

There are various ways to secure Web API. Let's discuss one by one.

Form Authentication, Authorization Filter.

Read in details view this blog - ASP.Net Web API Security
Basic Authentication in Web API

10. Http Get vs Http Post

GET and POST is 2 important HTTP verbs. HTTP (HyperText Transfer Protocol) manages the request-response between client and server.
GET vs POST is one of the most asked questions in an ASP.Net interview.

GET parameters included in URL
POST parameter included in the body

Get request shouldn't make any changes to the server
POST is to make changes to the server

GET request is idempotent
POST request is non-idempotent.

In a GET request, we can send data in plain text.
In a POST request, we can send binary as well as text data.

Top 10 differences between Http GET and Http POST

11. Can we use Web API with traditional ASP.Net Forms?

Yes, Web API can be used with ASP.Net Forms.
You can add Web API Controller and manage to route in Application Start method in Global.asax file.

12. Exception filters in ASP.Net Web API

Exception filter in Web API implements IExceptionFilters interface. Web API Exception filters execute when an action throws an exception at any stage.

13. Can we return View from ASP.Net Web API?

No, it is not possible in Web API as Web API creates HTTP based service.
It is available in MVC application.

14. What's new in ASP.Net Web API 2.0?

New features included in Web API 2 are -

1. Attribute-based routing

        [Route("product/{productid}/category")]
        public string Get(int productid)
        {
            return "value";
        }

2. CORS (Cross-Origin Resource Sharing) support
3. OWIN to Self Host Web API
4. Web API OData

15. How to restrict access to methods with an HTTP verb in Web API?

You can just add an attribute as shown below -

       [HttpGet]
        public HttpResponseMessage Test()
        {
            HttpResponseMessage response = new HttpResponseMessage();
            ///
            return response;
        }

       [HttpPost]
        public void Save([FromBody]string value)
        {

        }

16. How to make sure that Web API returns data in JSON format only?

To do this open "WebApiConfig.cs" file and add below line :
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"))
For detail explanation visit this blog - How to make sure that Web API returns JSON only.

17. How to give Alias name for an action method in Web API?

You can give Alias name by adding an attribute ActionName

       [ActionName("InertUserData")]
        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

18. Exception handling in Web API.

How we can handle errors in Web API?
Below classes helps to handle the exception in ASP.Net Web API.

  • ExceptionFilters
  • HttpError
  • HttpResponseException

19. How to host Web API?

Web API application can be hosted in 2 ways -

1. Self Hosting - Web API can be hosted in Console Application or Windows Service.
2. IIS Hosting - Web API can also be hosted with IIS and the process is similar to hosting a website.

20. How to consume Web API using HttpClient?

HttpClient was introduced in HttpClient class to communicate with ASP.Net Web API. This HttpClient class can be used in a console application or in an MVC application.

Click Here to see the implementation of Web API CRUD operation in MVC application using Entity Framework.

If you have more important Web API interview questions and answers, then please comment below.
Share this blog if you like it.

21. Parameters in Web API

Action methods in Web API accept parameters either as a query string in URL or with the request body.
For eg - To fetch particular product details the Get method requires an id parameter.


public IHttpActionResult GetProductMaster(int id)
        {
            ProductMaster productMaster = db.ProductMasters.Find(id);
            if (productMaster == null)
            {
                return NotFound();
            }

            return Ok(productMaster);
        }



In the same way, the Post method requires complex type parameter to post data to the server.


public IHttpActionResult PostProductMaster(ProductMaster productMaster)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.ProductMasters.Add(productMaster);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = productMaster.id }, productMaster);
        }



Similarly PUT method requires primitive data type i.e. id and complex parameter i.e. ProductMaster class.


        public IHttpActionResult PutProductMaster(int id, ProductMaster productMaster)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != productMaster.id)
            {
                return BadRequest();
            }

            db.Entry(productMaster).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductMasterExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

22. Can we consume Web API 2 in C# console application?

Yes, we can consume Web API 2 in Console Application, Angular JS, MVC or any other application.

Consume Web API 2 in Console Application

 23. Perform Web API 2 CRUD operation using Entity Framework.

With Web API we can perform CRUD operation using entity framework.
You can read one of my blog to see the implementation of Web API 2 CRUD operation using Entity Framework. Click Here

24. How to Enable HTTPS in Web API?

 As you know ASP.Net Web API runs over HTTP protocol. Suppose you want to serve your Web API to be accessible only over secure HTTP i.e. HTTPS and not over HTTP. To implement this you must use Filters.

Create a class and inherit that class with AuthorizationFilterAttribute and then check if the requested url has HTTPS or not.

You may see full implementation of How to enable HTTPS in Web API?

25. How to implement Basic Authentication in ASP.Net Web API?

Basic Authentication is a simple authentication mechanism where the client sends requests with an Authorization header with word Basic. In Basic Authentication, Authorization header contains a word Basic followed by base 64 encoded string.

The syntax for Basic Authentication -

Authorization: Basic username: password

You may see Basic Authentication implementation in Web API on the below link.

Basic Authentication in Web API

26. What is Token Based Authentication in Web API?

A better approach to secure .Net Web API is by authenticating users by a signed token. This is called token-based approach.
In Token-based authentication -

A client sends a request to the server with the credential. If the given credential is valid then the server sends a token to the client.
This token contains user details for the identification with an expiry time.
Once the client received the token, it uses this token to access API resources wherever authentication requires.
To implement Token-based authentication you need to install Microsoft.Owin from Nuget package.

27. What is content negotiation in .Net Web API?

In ASP.Net Web API, content negotiation is performed at the server-side. This is to determine the media type formatter to return the response to an incoming request.

28. What is ASP.Net identity?

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

29. What is Bearer Authenticating in .Net Web API?

Bearer authentication is also called as Token-based authentication.

30. Explain oData with ASP.Net Web API.

OData stands for Open Data Protocol, it is a Rest-based data access protocol. OData provides a way to query and manipulate data using CRUD operation. ASP.Net Web API supports OData V3 and V4.

To use OData in ASP.Net Web API, you need the OData package by running below command in Package Manager Console.

Install-Package Microsoft.AspNet.Odata

Hope these interview questions and answers are useful to you.
If you like this blog, then please share this on social media.

You may also like below blog-


Comments

Popular