Web API Interview Questions in Asp.net

Latest Asp.net Web API interview questions with answers for beginners. In this post we cover .net web api and .net core web api, so you may find different solution for same question (specified with version number).

C# web service interview questions
Asp.net Web API security interview questions

to create an api in .net we just need to add an roter atrribute on top of controller class [Route("api/[controller]")]

namespace WebTrainingRoom
{
    [Route("api/[controller]")]
    public class TestController : Controller
    {	
	    [HttpGet]
	    public IEnumerable<string> Get()
	    {
		    return new string[] { "value1", "value2" };
	    }
    }
}
  1. What is ASP.NET Web API?
    ASP.NET Web API is a framework for building HTTP based service, that can communicate using different data format like XML and JSON, Asp.Net Web service can reach to different clients like browsers, mobile, IoT devices, etc. WEB API Service is highly secure and can communicate asynchronously.
  2. Advantages of Using ASP.NET Web API
    • The most important advantage of using Web API is, it supports cross platform development, which is the key of any business success
    • It works on HTTP using HTTP verbs, which means any application can consume Asp.Net Web API to communicate with
    • Asp.Net Web API can be highly secure communication protocol, and it also supports asynchronous call, which can help improving performance and creating great user experience for any application.
    • Asp.net Web API can create response in XML and JSON format, can easily be integrated using different scripting language PHP, JavaScript etc.
    • Asp.net Core Web API can be hosted in outside IIS and even on different OS.
  3. What is the default MediaTypeFormatter in asp.net Web API?
    Default MediaTypeFormatter is XML, Means if we don’t explicitly specify any format, then data will be returned in XML format by default.
  4. What are the different MediaTypeFormatter in Web API?
    There are XmlFormatter, JsonFormatter, FormUrlEncodedFormatter, we can create any custom MediaTypeFormatter using custom class inherited from same base MediaTypeFormatter class.
  5. How to send action message back from Web API to client
    We should create HttpResponseMessage type post instead of void, then we can create a response object to send back to client.
    var returnMessage = Request.CreateResponse(HttpStatusCode.Created, c);
  6. How to send error message back from Web API to client

    We should create HttpResponseMessage type post instead of void, then we can create a response object with exception object, we can write try catch block this way.

    try                
    {
    }
    catch (Exception ex)
    {
        var returnErrMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        return returnErrMessage;
    }
  7. How to return only JSON or XML type from a Web API project?

    Well, we can fix the (Formatters) return type, we can remove any formatter (MediaTypeFormatter) from web API project just by adding few lines in “WebApiConfig.cs”

    In following example suppose we want to return only JSON type,
    So added config.Formatters.Remove(config.Formatters.XmlFormatter);

    public static class WebApiConfig                
    {
        public static void Register(HttpConfiguration config)
        {
                config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });
                    
            //Suppose we want to return only JSON type,then we can remove XML formatter this way.
            config.Formatters.Remove(config.Formatters.XmlFormatter);                
        }
    }
  8. What is the difference between WCF Service and ASP.NET Web API?

    Asp.net Web API is for building HTTP Services that can reach to different clients like browsers, mobile, IoT Devices, etc, but Web API is limited to HTTP based services, it can work only on HTTP protocol

    On the other hand WCF (Windows Communication Foundation) is designed for building service oriented architecture (SOA), we can build service using WCF that supports multiple transport protocol like HTTP, TCP, MSMQ, etc.

  9. Can we return View from Asp.net Web API?
    No, we can’t return view from Asp.net Web API, we can return data in JSON or XML format only, But, Yes we can return HTML from Asp.net Web API, which means any content embedded with different HTML tags like image, form etc can be returned from Web API
  10. How to return html content from web api?

    We can return html content from web api action result just by adding attribute [Produces("text/html")], Attribute indicate the result will be html content, can be a form, image, newsletter etc.

    [HttpGet("{id}")]
    [Produces("text/html")]
    public ActionResult<string> Get(int id)
    {
        string _result = "<b>Return HTML content using Web API method </b>";
        return _result;
    }
    

    Above solution, need some additional work to make it work for.net core version.

    In asp.net core, we need to create a string formatter class public class HtmlOutputFormatter : StringOutputFormatter and then register the class in configureServices method in startup file.

  11. What is Basic HTTP Authentication?
    Basic HTTP Authentication is the default mechanism, using Basic HTTP Authentication we can pass the authentication credential using HTTP request header, credential sent in string format like “username:password”, Take a look at the how Authentication Implemented in Asp.net Web API
  12. How to define a API in .net core 3.1?

    We can create api just by adding an api controller attribute class like example below.

    [ApiController]
    [Route("[controller]")]    
    public class OrderController : ControllerBase
    {
    
    }
    
  13. How to write custom get method name in .net web api
    We can specify custom name in using Route attribute on top of the ActionResult, we can write like [Route("GetCustomNameExample")]
    [Route("GetOrders")]
    [HttpGet]
    [ProducesResponseType(typeof(IEnumerable <Order>),(int)HttpStatusCode.OK)]
    public async Task <IActionResult> GetOrders()
    {               
    var orders = await _queryService.GetNewOrdersAsync();
    		  
    return Ok(orders);
    }	
    
    Note: this example was written in asp.net core 3.1 version, you may not find this if you are using older version.

    That we can have multiple get method in same api controller, below is the default get method of same controller

    [Route("")]
    [HttpGet]
    public IEnumerable<OrderItem> Get()
    {
    	var rng = new Random();
    	return Enumerable.Range(1, 5).Select(index =< new OrderItem
    	{
    		OrderDate = DateTime.Now.AddDays(index),
    		ProductId = rng.Next(-20, 55),
    			
    	})
    	.ToArray();
    }
    

    Now, if consumer does not know the custom get method name, the above get method will serve the purpose.

  14. What is the use of ProducesResponseType in web Api method, is it mandatory?

    First, let’s understand how that ProducesResponseType attribute was placed on top of the page actionresult

    [Route("GetOrders")]
    [HttpGet]
    [ProducesResponseType(typeof(IEnumerable <Order>),(int)HttpStatusCode.OK)]
    public async Task <IActionResult> GetOrders()
    {               
    var orders = await _queryService.GetNewOrdersAsync();
    		  
    return Ok(orders);
    }	
    

    To answer the question, no, the ProducesResponseType attribute is not mandatory, without that also api inherently sent the status code, but this attribute works like a mediator, which provide additional information like the type of object we want to return along with status code.

Latest Asp.net Web API Course and Interview Questions Answers
ASP.NET Course Online
Asp.net Course Online
free web api tutorial online
Interview Question Answers | Fresher Job Interview Tips