API Application Programming Interface connect services on internet and allow network data communication, software engineer touching concept for IoT, cloud computing, robotic process automation

Web API is an important application programming interface that enables web services over a broad range of browsers and devices such as tablets, mobile phones, etc. It is of significant importance for its lightweight and simpler services as well as being able to be used as a standalone web service application.

If you are a student of Web API or a professional who is developing their competence in this framework, you already know the importance of having a reliable resource of Web API interview questions. As the focus of Web API is practical, any collection of questions has to address the application of Web API in practical scenarios. These interview questions can also help you prepare for your dream job in this field.

Let us understand more about Web API by delving into these Web API Interview Questions, which will help you during a job interview or just to enhance your overall knowledge and understanding of this subject.

  • What is ASP.Net Web API?
  • What are the differences between Web API and WCF REST API?
  • What are the advantages of using ASP.Net Web API?
  • What are the several return types in ASP.Net Web API?
  • What is ASP.Net Web API routing?
  • What are Media type formatters in Web API?
  • What is the CORS issue in Web API?
  • How to secure an ASP.Net Web API?
  • What are the differences between HTTP Get and HTTP Post?
  • Can we use Web API with traditional ASP.Net Forms?
  • Web API Interview Questions

    1. What is ASP.Net Web API?

    A: ASP.Net Web API is a framework that helps in shaping and consuming HTTP based service. Clients dealing with mobile applications and web browsers can consume Web API.

    2. What are the differences between Web API and WCF REST API?

    A: Web API is suitable for HTTP-based services, while WCF REST API is ideal for Message Queue, one-way messaging, and duplex communication. WEB API supports any media format, even XML, JSON; while, WCF supports SOAP and XML format. ASP.Net Web API is ideal for building HTTP services, while WCF is perfect for developing service-oriented applications. To run Web API, there is no configuration required, while in the case of WCF, a lot of configuration is required to run it.

    3. What are the advantages of using ASP.Net Web API?

    A: The advantages of using ASP.Net Web API are mentioned below:

    • It completes support for routing
    • Is works as HTTP using standard HTTP verbs such as GET, DELETE, POST, PUT, to name a few, for all CRUD operations
    • It can be hosted in IIS as well as self-host outside of IIS
    • It supports OData
    • It supports validation and model binding
    • The response is generated in XML or JSON format by using MediaTypeFormatter

    4. What are the several return types in ASP.Net Web API?

    A: The various return types in ASP.Net Web API are:

    • IHttpActionResult
    • HttpResponseMessage
    • Void
    • Other Type – string, int, or other entity types.

    5. What is ASP.Net Web API routing?

    A: It is the process that determines the action and controller that should be called.

    The ways to incorporate routing in Web API include:

    • Attribute based routing
    • Convention based routing

    6. What are Media type formatters in Web API?

    A: The Media type formatter in Web API include:

    • MediaTypeFormatter – It is the base class that helps to handle serializing and deserializing strongly-typed objects.
    • BefferedMediaTypeFormatter – It signifies a helper class to allow asynchronous formatter on top of the asynchronous formatter infrastructure.
    Media type formatter

    7. What is the CORS issue in Web API?

    A: CORS is the acronym for Cross-Origin Resource Sharing. CORS solves the same-origin restriction for JavaScript. Same-origin means a JavaScript only makes AAJAX call for web pages within the same-origin.

    You have to install the CORS nuget package by using Package Manager Console to enable CORS in Web API.

    Open WebAPIConfig.cs file

    add config.EnableCors();

    Add EnableCors attribute to the Controller class and define the origin.

    [EnableCors(origins: “”, headers: “*”, methods: “*”)].

    8. How to secure an ASP.Net Web API?

    A: To secure an ASP.Net Web API, we need to control the Web API and decide who all can access the API and who cannot access it. Web API can be accessed by anyone who knows about the URL. 

    9. What are the differences between HTTP Get and HTTP Post?

    A: GET and POST are two important verbs of HTTP.

    • Parameters of GET are included in the URL; while parameters of POST are included in the body
    • GET requests do not make any changes to the server; while POST does make changes to the server
    • A GET request is idempotent; while a POST request is non-idempotent
    • In a GET request, data is sent in plain text; binary and text data are sent

    A: Web API can easily be used with ASP.Net Forms. You can add Web API Controller and route in Application Start method in Global.asax file.

    11.Exception filters in ASP.Net Web API

    A: Exception filters in Web API help in implementing IExceptionFilters interface. They perform when an action throws an exception at any point.

    12. Do we return Views from ASP.Net Web API?

    A: No, it is not possible as Web API creates an HTTP-based service. It is mostly available in the MVC application.

    13. What is new in ASP.Net Web API 2.0?

    A: The features introduced in ASP.NET Web API framework v2.0 are:

    • Attribute Routing
    • External Authentication
    • CORS (Cross-Origin Resource Sharing)
    • OWIN (Open Web Interface for .NET) Self Hosting
    • IHttpActionResult
    • Web API Odata

    14. How do we limit access to methods with an HTTP verb in Web API?

    A: An attribute has to be added as shown below:

    public HttpResponseMessage Test()
    HttpResponseMessage response = new HttpResponseMessage();
    return response;
    public void Save([FromBody]string value)

    15. How do we make sure that Web API returns data in JSON format only?

    A: To ensure that web API returns data in JSON format only, open “WebApiConfig.cs” file as well as add the below line:

    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“application/json”))

    To learn JSON format, you can also take up free online courses that will help you enhance your basic skills about the same.

    16. How to provide Alias name for an action method in Web API?

    A: By adding an attribute ActionName, an Alias name can be provided:

    // POST api/
    public void Post([FromBody]string value)

    17. How can we handle errors in Web API?

    A: Handling errors or exceptions in Web API can be done with the help of the following classes –

    • Using HttpResponseException –This exception class helps to return the HTTP status code specified in the exception Constructor.
    • Using HttpError – This exception class helps to return meaningful error code to the client as HttpResponseMessage.
    • Using Exception filters – Exception filters help in catching unhandled exceptions or errors generated in Web API and they can be used whenever the controller action method throws the unhandled error. 

    18. How to host Web API?

    A: There are two ways how Web API application can be hosted:

    • Self Hosting 
    • IIS Hosting 

    19. How to consume Web API using HTTPClient?

    A: HTTPClient is introduced in HTTPClient class for communicating with ASP.Net Web API. This HTTPClient class is used either in a console application or in an MVC application.

    20. Explain oData with ASP.Net Web API. 

    A: OData is the acronym for Open Data Protocol. It is a Rest-based data access protocol. OData provides a way to manipulate data by making use of CRUD operation. ASP.Net Web API supports OData V3 and V4.

    To use OData in ASP.Net Web API, you would need an OData package. You have to run the below command in the Package Manager Console.

    Install-Package Microsoft.AspNet.Odata

    21. Can we consume Web API 2 in C# console application?

    A: Yes, Web API 2 can be consumed in Console Application, MVC, Angular JS, or any other application.

    22. Perform Web API 2 CRUD operation using Entity Framework.

    A: CRUD operation can be performed by using entity framework with Web API.

    23. How to enable HTTPs in Web API?

    A: ASP.Net Web API runs over HTTP protocol. You can create a class and get a class with AuthorizationFilterAttribute. Now check if the requested URL has HTTPs.

    24. How to implement Basic Authentication in ASP.Net Web API?

    A: Basic Authentication in ASP.Net Web API can be implemented where the client sends a request with an Authorization header and word Basic. In Basic Authentication, the Authorization header contains a word Basic followed by a base 64 encoded string.

    The syntax for Basic Authentication –

    Authorization: Basic username: password

    25. What is Token Based Authentication in Web API?

    A: It is an approach to secure .Net Web API as it authenticates users by a signed token, also called a token-based approach.

    26. What is content negotiation in .Net Web API?

    A: In ASP.Net Web API, content negotiation is done at the server-side. This helps in determining the media type formatter especially when it is about returning the response to an incoming request.

    27. What is ASP.Net identity?

    A: ASP.Net identity is the membership management framework that Microsoft provides. It is very easily incorporated with Web API. This can help you to build a secure HTTP service.

    28. What is Bearer Authentication in .Net Web API?

    A: Bearer authentication is also known as Token-based authentication.

    29. What is REST?

    A: REST stands for Representational State Transfer. This is an architectural pattern that helps in exchanging data over a disseminated environment.

    REST architectural pattern treats all the services as resources and a client can access these resources by using HTTP protocol methods which include PUT, GET, POST, and DELETE.

    30. What is Not REST?

    A: The mentioned below are not REST:

    • A standard
    • A protocol
    • 3. A replacement of SOAP

    31. What are the differences between REST and SOAP?

    A: Here are some differences between REST and SOAP:

    SOAP stands for Simple Object Access Protocol REST stands for Representational State Transfer.
    SOAP is a protocol, called an XML REST is not a protocol but you can call it an architectural pattern example which is used for resource-based architecture.
    SOAP specifies both stateless as well as state-full implementation REST is completely stateless.
    SOAP applies message formats like XML; REST does not apply message formats like XML or JSON.
    To expose the service, SOAP uses interfaces and named operations; REST uses URI and methods like POST, GET, PUT, and DELETE for exposing resources (service).

    32. What are the differences between ASP.NET MVC and ASP.NET Web API?

    A: MVC is used to create web applications that can return views as well as data; while ASP.NET Web API is used to create restful HTTP services simply, which returns only data and no view. In MVC, the request is mapped to the actions name; while the request is mapped to the actions based on HTTP verbs in Web API.

    33. Is it true that ASP.NET Web API has replaced WCF?

    A: It is not true! It is rather just another way to build non-SOAP based services like plain XML or JSON string. It comes with additional advantages such as using HTTP’s full features and reaching more clients such as mobile devices, etc.

    34. Explain media Formatters in Web API 2

    A: These are classes that are responsible for response data. The Web API understands the request data format as well as sends data in the format as expected by the clients.

    35. Which protocol is supported by Web API?

    A:  The only protocol supported by Web API is HTTP. Therefore, it can be consumed by a  client that supports HTTP protocol.

    36. What are the similarities between MVC and Web API?

    A: Both MVC and Web API are based on the principle of Separation of concerns and concepts like controllers, routing, and models.

    37. What are the differences between MVC and Web API?

    A: MVC is used for developing applications that come with User interfaces. The Views in MVC are used to develop a User Interface. Web API is used for developing HTTP services. To fetch data, the Web API methods are called by other applications.

    38. Who can consume Web API?

    A: Web API is consumed by a client that supports HTTP verbs such as DELETE, GET, PUT, POST. They can quite easily be consumed by a client as Web API services do not need any configuration. Web API can be consumed very easily by portable devices.

    39. How are Requests mapped to Action methods in Web API?

    A: As Web API uses HTTP verbs, a client that can consume a Web API that needs ways to call the Web API method. A client can use the HTTP verbs to call the action methods of the Web API.

    Take a look at the example given below. In order to call a method like GetEmployee, client can use a jQuery method like:

    $.get(“/api/Employees/1”, null, function(response) {

    Therefore, the method name above has no mention. As an alternative, GetEmployee method can be called by using the GET HTTP verb.

    The GetEmployee method can be defined as:

     public void GetEmployee(int id)

    As the GetEmployee method can be seen decorated with the [HttpGet] attribute, different verbs to map the different HTTP requests have to be used:

    • HttpGet
    • HttpPut 
    • HttpPost
    • HttpDelete

    40. Can the HTTP request be mapped to the action method without using the HTTP attribute?

    A: For the action method, there are two ways to map the HTTP request. The first way is using the trait on the action method. The second way is naming the method that starts with the HTTP verb. Taking as an example, to define a GET method, it can be defined as:

    public void GetEmployee(int id)

    As it can start with GET, the above-mentioned method can be automatically mapped with the GET request.

    41. How to add certificates to a website?

    A: To add the certificate to the website, you can follow the steps mentioned below:

    • You have to go to run type command mmc
    • Now click on Ok
    • The certificate add window is open now

    42. Write a LINQ code for authenticating the user?

    A: public static bool Login(string UN, string pwd)

    {StudentDBEntities students = new StudentDBEntities()students.sudent.Any(e => e.UserName.Equals(UN) && e=>e.Password.Equlas(UN)) // students has more than one table}

    43. How to navigate another page in jQuery?

    A: using widow.location.href = “~/homw.html”;

    44. How to enable SSL to ASP.NET web?

    A: In order to enable SSL to ASP.NET web, you can click on project properties where you can see this option.

    45. How to mention Roles and users using Authorize attribute in Web API?

    // Restrict by Name
    public class StudentController : ApiController{}
    // Restrict by Role[Authorize(Roles=”Administrators”)]
    public class StudnetController : ApiController{}

    46. Can we apply constraints at the route level?

    A: Yes, it can be applied.

    public User GetStudentById(int id) { … }
    public User GetStudentByName(string name) { … }

    You can select the first route whenever the “id” segment of the URI is an integer. Or else, you can choose the second route.

    47. How to enable attribute routing?

    A: To enable attribute routing, MapHttpAttributeRoutes(); method can be called in the WebApi config file.

    public static void Register(HttpConfiguration config)
    // Web API routes
    // Other Web API configuration not shown.

    48. How parameters get the value in Web API?

    A: Parameters get value in Web API in the following way:

    • Request body
    • URI
    • Custom Binding

    49. Why is the “api/” segment used in Web API routing?

    A: “api/” segment is used to avoid collisions with ASP.NET MVC routing

    50. Is it possible to have MVC kind of routing in Web API?

    A: It is possible to implement MVC kind of routing in Web API.

    51. Where is the route defined in Web API?

    A: It is placed in the App_Start directory.

    App_Start –> WebApiConfig.cs
    name: “myroute”,
    routeTemplate: “api/{controller}/{id}”,
    defaults: new { id = RouteParameter.Optional }

    52. How do you construct HtmlResponseMessage?

    public class TestController : ApiController
    A: To construct HtmlResponseMessage, you can consider the following way:
    public HttpResponseMessage Get()
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, “value”);
    response.Content = new StringContent(“Testing”, Encoding.Unicode);
    response.Headers.CacheControl = new CacheControlHeaderValue()
    MaxAge = TimeSpan.FromMinutes(20)
    return response;

    53. What are the default media types supported by Web API?

    A: The default media types that are supported by Web API are XML, form-urlencoded data, JSON, BSON. The other media types supported can be done by writing a media formatter.

    54. What is the disadvantage of “Other Return Types” in Web API?

    A: The major disadvantage of “Other Return Types” in Web API is that error codes like 404 errors will not directly be returned.

    55. What is the namespace for IHttpActionResult return type in Web API?

    A: System.Web.Http.Results namespace

    56. Why is Web API important?

    We have several other technologies similar to Web API yet it is the most important and preferred over others for several reasons –

    • Web API has the most lightweight architecture and provides an easy interface for websites and client applications to access data. 
    • It uses low bandwidth. This makes it ideal for even small bandwidth devices, for instance, smartphones.
    • It can create non-SOAP-based HTTP services.
    • It can be consumed by a range of clients including web browsers, desktop and mobile applications.
    • Web API is based on HTTP which makes it convenient to define, consume or expose using REST-ful services. 
    • It fits best with HTTP verbs for operations such as Create, Read, Delete or Update.
    • Web API is more useful from the business point of view and finds its applications in UI/UX to increase web traffic and interest in a company’s services or products. 
    • It can support a plethora of text and media formats such as JSON, XML, etc. 
    • It can also support Open Data (OData) protocol. 
    • It is most suitable for the MVC pattern which makes it ideal for experienced developers in that pattern. 
    • It can be easily built using technologies such as ASP.NET, JAVA, etc. 
    • It is considered the best to create resource-oriented services. 

    57. Which .NET framework supports Web API?

    The .NET framework version supported by Web API includes version 4.0 and above. 

    58. Which open-source library is supported by Web API for JSON serialization?

    JSON.NET library is a high-performance JSON framework used for JSON serialization by Web API. 

    59. What are the advantages of using REST in Web API?

    REST offers numerous advantages in Web API that include –

    • Lightweight architecture and easy to use 
    • Offers flexibility
    • Allows less data transfer between client and server
    • Handles various types of data formats
    • Its lightweight architecture makes it optimal for use in mobile applications
    • Uses simple HTTP calls for inter-machine communication

    60. When do we need to choose ASP.NET Web API?

    In today’s hyper-connected digital world, we are moving web-based services towards mobile applications. That means we need an API that is lightweight, secure, safe and compatible with these smart devices. The ASP.Net Web API is a framework that fulfils all these requirements for building HTTP services consumed by a vast array of clients including browsers and modern devices such as mobile phones, tablets, etc. 

    61. What do you understand by TestApi in Web API?

    TestAPi in Web API refers to a utility library that allows developers to create testing tools as well as automate tests for a .NET application. 

    62. How can we handle an error using HttpError in Web API?

    The HttpError method is used in Web API to throw the response body’s error information. One can also use the “CreateErrorResponse” method along with this one. 

    63. Can we consume Web API 2 in the C# console application?

    Yes. It is possible to consume Web API 2 in Console Application, MVC, Angular JS or any other application.

    64. How to implement Basic Authentication in ASP.Net Web API?

    Basic Authentication in ASP.Net Web API is one where the client will send a request using the word Basic with an Authorization header, followed by a base 64 encoded string.

    The syntax for Basic Authentication –

    Authorization: Basic username: password

    65. Give an example of the parameter in Web API.

    Parameters are used in Web API to determine the type of action you take on a particular resource. Each parameter consists of a name, value type and description that has the ability to influence the endpoint response.

    You can use the query API to get information about various entities within a data source. 

    The Get Method employs multiple primitive parameters. For instance, the Get method needs id parameter to get product details –

    public IHttpActionResult GetProductMaster(int id)
    ProductMaster productMaster = db.ProductMasters.Find(id);
    if (productMaster == null)
    return NotFound();
    return Ok(productMaster);
    In the same way, the Post method will require complex type parameters to post data to the server.
    public IHttpActionResult PostProductMaster(ProductMaster productMaster)
    if (!ModelState.IsValid)
    return BadRequest(ModelState);
    return CreatedAtRoute(“DefaultApi”, new { id = productMaster.id }, productMaster);
    Similarly PUT method will require primitive data type example for id and complex parameter i.e. ProductMaster class.
    if (id != productMaster.id)
    return BadRequest();
    db.Entry(productMaster).State = EntityState.Modified;
    catch (DbUpdateConcurrencyException)
    if (!ProductMasterExists(id))
    return NotFound();

    66. Give an example to specify Web API Routing. 

    Here is an example of Web API routing –

    name: "MyRoute,"//route name  
    routeTemplate: "api/{controller}/{action}/{id}",//as you can see "API" is at the beginning.  
    defaults: new { id = RouteParameter.Optional }  

    67. How to register an exception filter globally?

    You can use the following code to register an exception filter globally –

    GlobalConfiguration.Configuration.Filters.Add (new MyTestCustomerStore.NotImplExceptionFilterAttribute());  

    68. What are the different HTTP methods used in Web API?

    Though there are a variety of HTTP verbs or methods, the most important and frequently used ones are GET, PUT, POST and DELETE.  

    GET – It is used to retrieve information of the resource at a specified URI.

    PUT – The PUT method is used to update the values of a resource at a specified URI.

    POST –POST method is used to create a new request and send data to the respective server. 

    DELETE –This method is used to remove the current resource at a specified URI.

    The functionality of these HTTP verbs can be summed up using the acronym CRUD in which each letter corresponds to different action –

    C stands for Create or POST (creating data)

    R stands for Read or GET (data retrieval)

    U stands for Update or PUT (updating data)

    D stands for Delete or DELETE (deleting data)

    Other less frequently used HTTP verbs or methods as per the requirement include –

    HEAD –This method works the same way as the GET method and is primarily used to transfer the header section.

    OPTIONS –This method helps identify and describe the communication option for a specific resource.

    CONNECT –It is used to establish two-way communication between the server and the desired destination with the help of a given URI. 

    TRACE – This method is used for diagnostic purposes to invoke a loop-back message along the target path and use that data for testing. 

    69. What is HttpConfiguration in Web API?

    HttpConfiguration refers to the global set of services used to override the behaviour of the default Web API. It has the following properties –

    • ParameterBindingRules
    • Formatters
    • MessageHandlers
    • DependencyResolver 
    • Services 

    70. Explain the code snippet to show how we can return 404 errors from HttpError.

    Here’s the Code for returning 404 error from HttpError – 

    string message = string.Format(“TestCustomer id = {0} not found”, customerid);
    return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);

    71. What is the code used to register an exception filter from the action?

    One can register an exception filter using the following code –

    public TestCust GetMyTestCust (int custno)
    //write the code

    72. What are the testing tools or API for developing or testing web API?

    • CFX
    • Axis
    • Jersey API 
    • Restlet 

    73. How can you pass multiple complex types in Web API?

    Two ways to pass multiple complex types in Web API include – Newtonsoft array and using ArrayList. 

    74. What is the code for passing ArrayList in .NET Web API?

    ArrayList paramList = new ArrayList();
    Category c = new Category { CategoryId = 1, CategoryName =“MobilePhones”};
    Product p = new Product { Productcode = 1, Name = “MotoG”, Price = 15500, CategoryID = 1 };

    75. What is an HTTP status code? 

    HTTP status codes are three-digit integers issued by the server in response to the request made by the client, where each number specifies a meaning. 

    76. How are different HTTP Status Codes categorized?

    All HTTP status codes are categorized into five classes. These include –

    • 1xx (Informational) – It indicates that the server has received a certain request and the process is continuing. 
    • 2xx (Successful)–It indicates that the request was successful and accepted. 
    • 3xx (Redirection)–It indicates that the request has been redirected and its completion will require further action or steps. 
    • 4xx (Client Error)–It indicates that the request for the web page cannot be reached as either it is unavailable or has bad syntax. 
    • 5xx (Server Error)–It indicates that the server was unable to complete a certain request even though the request seems valid. 

    77. What is the commonly observed HTTP response status code?

    There are many HTTP codes that are visible and others that are not visible at first but can be observed by the administrator using browser extensions or certain tools. Identifying and rectifying these errors is crucial to enhance the user experience and optimize search engine ranking over the web.  

    Here are the most commonly seen HTTP status codes at a glance –

    • Status code 200 – request is ok.
    • Status code 201 – Created 
    • Status code 202 – Accepted 
    • Status code 204 – No content 
    • Status code 301 – Moved permanently 
    • Status code 400 – Bad request 
    • Status code 401 – Unauthorized 
    • Status code 403 – Forbidden 
    • Status code 404 – Not found 
    • Status code 500 – Internal server error 
    • Status code 502 – Bad gateway 
    • Status code 503 – Service Unavailable 

    78. How do website owners avoid HTTP status codes?

    To ensure that the website is running smoothly and offers an optimal user experience, the administrator or website owner has to work consistently to keep automatically generated error codes to the minimum and also to identify 404 errors. 

    The 404 HTTP status code can be avoided by redirecting users by a 301 code to the alternative location such as the start page. The bounce-back rate of website visitors can also be decreased with the manual creation of error pages. 

    79. Name method that validates all controls on a page?

    Page.Validate() method system is executed to validate all controls on a page.

    80. What is the use of DelegatingHandler?

    DelegatingHandler is a process used to develop a custom server-side HTTP message handler in ASI.Net Web API and chain message handlers together.

    81. What do you mean by Internet Media Types?

    Formerly known as the MIME type, it refers to the standard design for identifying content on the internet such as the type of information a piece of data contains.  

    For example, if we receive a file over the email as an attachment, this identifier can be useful in knowing the media type of the attachment information contained in the header so that the browser can launch the appropriate plug-in.

    It is a good practice to know information on media types as every internet media type has to comply with the following format –

    [type]/[tree.] (Optional)[subtype][+suffix](Optional)[;parameters]

    Each media type must have the ‘type’ and the ‘subtype’ that indicates the type of information it contains. For instance,   

    Image– type/png- subtype

    Application– type/rss- subtype+xml

    82. Can a Web API return an HTML View?

    Web API cannot return an HTML view. If you want to return views, it is best to use MVC. 

    83. What is the status code for “Empty return type” in Web API?

    The status code 204 will return empty content in the response payload body.  

    84. Can you elaborate on different Web API filters?

    Filters are used to add extra logic before or after specific stages of request processing within the Web API framework. 

    There are different types of filters. Some built-in ones handle tasks such as authorization, response caching, etc. while custom filters can be created to handle concerns like error handling, authorization, etc.

    Filter run within the ASP.Net pipeline, also referred to as the filter pipeline and various types of filter depending on the execution at a particular stage in this filter pipeline include –

    • Authentication filter –It helps to authenticate user details and HTTP requests.
    • Authorization filter –It runs before controller action to determine whether the user is authorized or not. 
    • Resource filter –It runs after authorization and runs code before the rest of the filter pipeline. For example – OnResourceExecuted runs code after the rest of the pipeline gets completed.  
    • Action filter –It is used to add extra logic before action gets executed and has the ability to change the result returned from a particular action. 
    • Exception filter –It is used when controller action throws unhandled errors that occur before the response body is written.
    • Override filter –it is used to change the action methods or other filters. 
    • Result filter –It runs code either before or after the execution of action results. 

    85. What is the difference between ApiController and Controller?

    ApiController specializes in returning data arranged in series and sent to the client.

    public class TweetsController : ApiController
             // GET: /Api/Tweets/  
            public List<Tweet> Get()
              return Twitter.GetTweets();

    Controller, on the other hand, provides normal views and handles HTTP requests. 

    public class TweetsController : Controller 
            // GET: /Tweets/  [HttpGet]  public ActionResult Index() 
               return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);  

    86. What is the difference between XML and JSON?

    XML is an acronym for eXtensible Markup Language and is designed to store and send data. JSON is an acronym for JavaScript Object Notation and is used to store and transfer data when data is sent from a server to a web page.

    Except for storing data in a specific format, XLM does not do much whereas JSON is a lightweight and easy to understand format for storing data, widely used in JavaScript. 

    87. What do you mean by Caching?

    Caching refers to the technique of storing data in temporary storage in cache for future use. It keeps copies of all frequently used data as well as files in the cache which enables the website to render faster. It also helps improve scalability so that the data can be directly retrieved from the memory when it is needed in the future. 

    The simplest cache in ASP.Net Web API is based on IMemoryCache.

    Some key advantages of Caching include –

    • Minimizes database hits
    • Helps web pages render faster
    • Reduces network costs
    • Faster execution of process 
    • Highly efficient for both client and server
    • Reduces load time on the server
    • Best page management strategy to improve application’s performance 

    88. What are the types of Caching?

    There are different types of caching in ASP.NET Web API. These are –

    • Page output caching –This type of caching stores the recently used copy of the data in the memory cache to improve webpage performance. The cached output is fetched directly from the cache and sent to the application.

    Here’s the code to implement page output caching –

    <%@ OutputCache Duration="30" VaryByParam="*" %>
    • Page fragment caching –In this form of caching, only fragments of data or web pages are cached instead of the entire page. It is helpful when the webpage contains dynamic and common sections and the user wants to cache some portions of it. 
    • Data caching –In this form of caching, data is stored in temporary storage so that it can be retrieved later. Here is the syntax to store data using the Cache API –

    Cache[“key”] = “value”;

    Web API FAQs

    What is Web API and how it works?

    A web API is an interface that allows you to access and manipulate data over the internet. It is typically used to access data from a web server, and can be used to create web applications or websites. It can be developed with the help of different technologies such as ASP.NET, or Java.

    What is Web API in C# Corner?

    A programming interface type that provides communication between software applications. It is often used to provide the interface for client applications and websites. It can also be used to access and save data from a database.

    What are the types of API?

    There are mainly four types of API used for web-applications. They are as follows:
    – public,
    – partner,
    – private, and
    – composite.

    What is Web API example?

    The full form of API is Application Programming Interface and it can extend the functionality of a web browser. An API would allow a third party such as Facebook to directly access the various functions of an external application, such as ordering a product on Amazon.

    These Web API interview questions cover the basic ground of Web API and make it easier for the students and professionals to clarify their fundamentals on this subject. For some of the industry-leading online courses on Web API, you can head to Great Learning Academy and upskill in this field. 

    Also Read Top 25 Common Interview Questions


    Previous articleSony and Tencent now own almost a third of the “Elden Ring” studio FromSoftware
    Next articleThe best video games for August 2022