In this article, I have provided a list of top ASP.NET web api interview questions, to improve web-API developer interview knowledge or check any developers knowledge.

1. What is ASP.NET Web-API?

ASP.NET Web-API is a framework, which is used to create HTTP services, which we can use to develop web, mobile or desktop applications.

Using Web-API we can get data from API services in JSON or XML format. So, using Web-API, we can expose our data to mobile as well as Web platforms at the same time.

You may like to read: Basics of Web-API

2. What are the Advantages of using Web-API?
  • It is lightweight architecture and ideal for devices that have limited bandwidth like smartphones.
  • ASP.NET Web API is built on top of ASP.NET and supports ASP.NET request/response pipeline
  • ASP.NET Web API supports different formats of response data. Built-in support for JSON, XML, BSON format.
  • It also supports OData.
  • The basic CRUD operations are mapped to the HTTP protocols, like GET, POST, PUST, DELETE.
  • Web API 2 now supports attribute routing as well with convention routing.
  • It can be hosted in IIS, Self-hosted or other web server that supports .NET 4.0+.
  • It also supports Model validation and binding.
3. What are the new features in ASP.NET web-api 2?

Here are the new features of Web-API 2:

  • Attribute Routing, a new routing attribute
  • OWIN (Open Web Interface for .NET) self host
  • IHttpActionResult return type
  • CORS (Cross-Origin Resource Sharing)
  • HttpRequestContext
  • ODATA Improvements, as it support for $expand, $select in OData Service.
  • Filter Overrides
  • ByteRangeStreamContent
  • Simplified unit testing of API Controllers using IHttpActionResult.
4. Name all type of Action Results present in Web-API 2

Web-API controller can return 4 type of ActionResults

  1. Void : returns no data, 204 (No Content)
    public class ValuesController : ApiController
    {
        public void Post()
        {
        }
    }?
  2. HttpResponseMessage: Convert directly to an HTTP response message.
    public class ValuesController : ApiController
    {
        public HttpResponseMessage Get()
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
            response.Content = new StringContent("hello", Encoding.Unicode);
            response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                MaxAge = TimeSpan.FromMinutes(20)
            };
            return response;
        } 
    }?
  3. IHttpActionResult: Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.

  4. Other type:Write the serialized return value into the response body; return 200 (OK).
    public class ProductsController : ApiController
    {
        public IEnumerable<Product> Get()
        {
            return GetAllProductsFromDB();
        }
    }?
5. Which protocal is suppported by web-api?

Web App supports HTTP protocol.

6.  By default, which status is returned for exception /errors in web-api?

500- Internal server error

7. What are main return types supported by Web API?

Web API can return data depending on requirements, there are many GET,POST,PUT etc methods which return data based on requirements.

8. What is attribute routing in web-api?

ASP.NET web api 2 supports routing, along with convention-based routing. Convertional based routing is default routing and have route like this

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

so, all the incoming request must in the above format.

Using Attribute routing, we can add spcific routing url, which can be user friendly, suppose I have api controller with getstudent method

[Route("student/{studentid}/class")]
public IEnumerable<Author> GetStudentClassByName(int studentid) {
 }

To Enable Attribute routing, you need to register it in WebAPIConfig file

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
9. How do you return View from web-api?

No, we can’t return a view from ASP.NET Web API as Web API creates HTTP services that render raw data but you can return image response, read here.

10. Can Web-API replace WCF?

Not, WEB API can not replace WCF completly. In fact, it is another way of building non-SOAP based services, i.e., plain XML or JSON string.

11. List Difference between Web API and WCF?

Here is the complete tabular comparison

wcf-webapi-interview-questions-min.png

12. What is the difference between MVC and Web API?

ASP.NET MVC framework is used to develop web applications that generate HTML pages called as Views, as well as data in it. ASP.NET MVC facilitates in rendering HTML easily by taking data from database like SQL server.

While, Web API is used to build non-Soap services,  HTTP services, that reach more clients by generating data in raw format, for example, plain XML or JSON string.

13. What is CORS in Web-API?

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.

You can simply enable CORS in Web-API,  by adding the below code in your Web API

public static void Register(HttpConfiguration config)
{
    // New code
    config.EnableCors();
}

You might have to install Nuget Package : Microsoft.AspNet.WebApi.Cors

If you want to enable CORS for only a single API Controller, can you do it using EnableCors Attribute

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}
14.  Explain about OWIN?

OWIN stands for Open Web Interface for .NET. OWIN is an abstraction between .NET web servers and web applications. OWIN decouples the web application from the server, which makes OWIN ideal for self-hosting a web application in your own process, outside of IIS.

You may like to read: Token based authentication in C# using Web API

15. What are Web-API Filters?

With Web-API filters, we can check the authenticity, authorization, and can also use filters for converting the result.

You can also use filters for other purposes also. Here are the types of Web-API filters:

  • Authorization Filter: Used to force users or clients to be authenticated before action methods execute.
  • Action Filter: Used to add extra logic before or after action methods execute.
  • Exception Filter: When there can be an exception in the Web-API pipeline, then we can use Exception Filter with its help we can track that exception and send the custom message to the client.
  • Override Filter: Sometime we may need to override the built-in filters, this is where Override filter help, it can be used to customize the behavior of other filters for individual action method.