Web API Interview Questions and Answers

1. What is Web API

Web API is Microsoft's HTTP based services. It is used to develop REST based services to help Web, Mobile applications to consume those services.

2. What are the advantages of Web API

  • Web API helps creating HTTP bases services for performing CRUD (get, post, put, delete) operations
  • Provides routing
  • Provides response in JSON, XML format using MediaTypeFormatter
  • Provides Authentication, Exception Handling features
  • Allows Cross Domain application to access Web API by enabling Cors in the application
  • It supports Model Binding and Validation of Model
  • Supports IIS as well as Self hosting of the services
  • Support for OData

3. Difference Between MVC and Web API

  • MVC controller inherits from Controller class where as Web API controller inherits from ApiController class
  • MVC controller returns View and Partial View page, where as Web API doesn't return View and Partial View page
  • MVC supports ViewBag, ViewData & TempData where as Web API does not support it
  • MVC supports ResultFilter where as Web API doesn't support ResultFilter

4. What are the new features introduced in Web API 2

  • Attribute Routing
  • CORS support
  • OData support
  • Async Support
  • IHTTPActionResult Support
  • OWIN Self Hosting Support

5. How to set default formatting of the Web API services to JSON?

  • Open WebAPI.config file in App_Start folder and write the below statements to set the JSON as default formatter for the services.
  •  public static class WebApiConfig     {
            public static void Register(HttpConfiguration config)
            {
                config.Formatters.Clear();
                config.Formatters.Add(new JsonMediaTypeFormatter());

                config.MapHttpAttributeRoutes();

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }


6. How Exception can be handled in Web API

  • Exception handling can be implemented directly in the action method by returning HttpResponseException as shown below:
  •         public IHttpActionResult GetUser()         {
                User usr = new Models.User();
                if (usr == null || string.IsNullOrEmpty(usr.Username))
                {
                    var response = new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
                        Content = new StringContent("User doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
                        StatusCode = HttpStatusCode.NotFound
                    };
                    throw new HttpResponseException(response);
                }
                return Ok();
            }
  • Exception Filter: We can implement custom class which inherits from ExceptionFilterAttribute and add the OnException method in that class to implement it. Once the class and method is ready we need to call that method inside WebApi.config file in App_Start folder as shown below and after that whenever service has any Exception, it will handle the exception and return the result as written in our AppExceptionFilter class.
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Filters.Add(new AppExceptionFilter());

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }


    public class AppExceptionFilter: ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            string exceptionMessage = string.Empty;
            var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("An unhandled exception was thrown by Service."),  
                    ReasonPhrase = "Internal Server Error. Please Contact your Administrator."
            };
            actionExecutedContext.Response = response;
        }
    }