All interview topics
Full-Stack, Web & Mobile

ASP.NET Web API Interview Questions and Answers

Practice ASP.NET Web API interview questions and answers organized by difficulty, with revealable explanations and related topics.

32 questionsEntry → Expert

Entry questions

1 questions
  1. Question 1
    Entry

    What is ASP.NET Web API?

    • ASP.NET Web API
    Reveal 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.

Senior questions

9 questions
  1. Question 1
    Senior

    How to Return View from ASP.NET Web API Method?

    • ASP.NET Web API
    Reveal 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.

  2. Question 2
    Senior

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

    • ASP.NET Web API
    Reveal 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
  3. Question 3
    Senior

    How can we provide an alias name for ASP.NET Web API Action?

    • ASP.NET Web API
    Reveal answer

    We can provide an alias name for ASP.NET 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);
    }
    
  4. Question 4
    Senior

    What is ASP.NET Web API OData?

    • ASP.NET Web API
    Reveal 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.

  5. Question 5
    Senior

    How to register exception filter globally?

    • ASP.NET Web API
    Reveal answer

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

    GlobalConfiguration.Configuration.Filters.Add(new MyTestCustomerStore.NotImplExceptionFilterAttribute());
    
  6. Question 6
    Senior

    What is Delegating Handler?

    • ASP.NET Web API
    Reveal answer

    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 ...
        var response = await base.SendAsync(request, cancellationToken);
        var responseDate = response.Headers.Date;
        // do something with the date ...
        return response;
      }
    }// ...
    GlobalConfiguration.Configuration
    .MessageHandlers
    .Add(new DateObsessedHandler());
    
  7. Question 18
    Senior

    Explain briefly CORS (Cross-Origin Resource Sharing)?

    • ASP.NET Web API Web Security
    Reveal 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.

  8. Question 19
    Senior

    Why are the FromBody and FromUri attributes needed in ASP.NET Web API?

    • ASP.NET Web API
    Reveal answer

    When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process calledparameter binding. By default, Web API uses the following rules to bind parameters: If the parameter is a simple type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. For complex types, Web API tries to read the value from the message body, using a media-type formatter. So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter. So, to answer your question, the need of the [FromBody] and [FromUri] attributes in Web API is simply to override, if necessary, the default behaviour as described above.

  9. Question 20
    Senior

    What's the difference between OpenID and OAuth?

    • ASP.NET Web API Web Security
    Reveal answer

    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.

Junior questions

7 questions
  1. Question 2
    Junior

    Explain the usage of HttpResponseMessage ?

    • ASP.NET Web API
    Reveal answer

    A HttpResponseMessage allows us to work with the HTTP protocol (for example, with the headers property) and unifies our return type. In simple words an HttpResponseMessage is a way of returning a message/data from your action.

    // GetEmployee action
    public HttpResponseMessage GetEmployee(int id)
    {
      Employee emp = EmployeeContext.Employees.Where(e => e.Id == id).FirstOrDefault();
      if (emp != null)
      {
        return Request.CreateResponse<Employee>(HttpStatusCode.OK, emp);
      }
    else
    {
      return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee Not Found");
    }
    }
    
  2. Question 3
    Junior

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

    • ASP.NET Web API
    Reveal 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

  3. Question 4
    Junior

    What New Features are Introduced in ASP.NET Web API 2.0?

    • ASP.NET Web API
    Reveal answer

    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
    
  4. Question 5
    Junior

    What exactly is OAuth (Open Authorization)?

    • ASP.NET Web API
    Reveal 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 )
    
  5. Question 6
    Junior

    What is the difference between ApiController and Controller ?

    • ASP.NET Web API
    Reveal 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();
      }
    }
    
  6. Question 7
    Junior

    Which status code used for all uncaught exceptions by default?

    • ASP.NET Web API
    Reveal 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;
    }
    
  7. Question 8
    Junior

    What are main return types supported in Web API?

    • ASP.NET Web API
    Reveal 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 serialised return value into the response body

Expert questions

6 questions
  1. Question 7
    Expert

    Why should I use IHttpActionResult instead of HttpResponseMessage ?

    • ASP.NET Web API
    Reveal answer

    Here 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. Long story short - it is not IHttpActionResult versus HttpResponseMessage . Basically, it is how you want to create the response.

  2. Question 8
    Expert

    Explain the difference between WCF, Web API, WCF REST and Web Service?

    • API Design ASP.NET Web API REST & RESTful
    Reveal 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. 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

  3. Question 9
    Expert

    Explain briefly OWIN (Open Web Interface for .NET) Self Hosting?

    • ASP.NET Web API
    Reveal 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.

  4. Question 10
    Expert

    Could you clarify what is the best practice with Web API error management?

    • ASP.NET Web API
    Reveal answer

    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.

  5. Question 11
    Expert

    Explain advantages/disadvantages of using HttpModule vs DelegatingHandler ?

    • ASP.NET Web API
    Reveal 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.

  6. Question 12
    Expert

    What is difference between WCF and Web API and WCF REST and Web Service?

    • ASP.NET Web API
    Reveal 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. 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

Mid questions

9 questions
  1. Question 9
    Mid

    In OOP, what is the difference between the Repository Pattern and a Service Layer?

    • ASP.NET ASP.NET MVC Design Patterns Software Architecture ASP.NET Web API
    Reveal answer

    Repository Layer gives you additional level of abstraction over data access. Service Layer exposes business logic, which uses repository or a set of repositories as UnitOfWork In ASP.NET MVC + EF + SQL Server, I have this flow of communication: Views <- Controllers -> Service layer -> Repository layer -> EF -> SQL Server Service layer -> Repository layer -> EF This part operates on models. Views <- Controllers -> Service layer This part operates on view models.

  2. Question 10
    Mid

    Name types of Action Results in Web API 2

    • ASP.NET Web API
    Reveal 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).

  3. Question 11
    Mid

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

    • ASP.NET Web API
    Reveal 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.

  4. Question 12
    Mid

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

    • ASP.NET Web API
    Reveal 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) { ..... }
    
  5. Question 13
    Mid

    How to restrict access to Web API method to specific HTTP verb?

    • ASP.NET Web API
    Reveal 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);
    }
    
  6. Question 14
    Mid

    Explain the difference between MVC vs ASP.NET Web API

    • ASP.NET Web API ASP.NET MVC
    Reveal 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.

  7. Question 15
    Mid

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

    • ASP.NET Web API WCF
    Reveal 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

  8. Question 16
    Mid

    Compare WCF vs ASP.NET Web API?

    • ASP.NET Web API WCF
    Reveal 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.

  9. Question 17
    Mid

    What are the differences between Web API and Web API 2?

    • ASP.NET Web API
    Reveal answer

    Attribute Routing OWIN self host IHttpActionResult CORS HttpRequestContext Betters Testability ODATA Improvements Filter Overrides ByteRangeStreamContent