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.

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 significant 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 developer who are already familair to MVC pattern.

WCF need 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 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 are 2 important HTTP verbs. HTTP (Hyper Text Transfer Protocol) manage 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 request body.
For eg - To fetch a particular product details the Get method requires a 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, Post method requires complex type parameter to post data to 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 client sends requests with Authorization header with word Basic. In Basic Authentication, Authorization header contains a word Basic followed by base 64 encoded string.

Syntax for Basic Authentication -

Authorization: Basic username:password

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

Basic Authentication in Web API



26. What is Token Based Authentication in Web API?

Answer coming soon...

27. How to implement Token Based Authentication in ASP.Net Web API?

Answer coming soon...

28. What is ASP.Net identity in Web API?

Answer coming soon...

29. How to use Bearer Token for Authenticating Web API?

Answer coming soon...

30. Explain oData with ASP.Net Web API.

Answer coming soon...

31. What is OWIN used for in Web API?


Comments

Popular