0% found this document useful (0 votes)
79 views28 pages

Web Api

Uploaded by

Ranjith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views28 pages

Web Api

Uploaded by

Ranjith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

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.

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

10. Can we use Web API with traditional ASP.Net Forms?

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.

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.
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.

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

How do we limit access to methods with an HTTP verb in Web


API?

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

[HttpGet]
public HttpResponseMessage Test()

HttpResponseMessage response = new HttpResponseMessage();

///

return response;

}
[HttpPost]
public void Save([FromBody]string value)

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”))

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

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

[ActionName(“InertUserData”)]
// POST api/

public void Post([FromBody]string value)

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. 

How to host Web API?

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

 Self Hosting 
 IIS Hosting 

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.

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

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.

Perform Web API 2 CRUD operation using Entity Framework.

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

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.

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

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.

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.

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.

What is Bearer Authentication in .Net Web API?

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

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.

What is Not REST?

A: The mentioned below are not REST:

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

What are the differences between REST and SOAP?

A: Here are some differences between REST and SOAP:


 SOAP stands for Simple Object Access Protocol; while, REST stands for
Representational State Transfer.
 SOAP is a protocol, called an XML; while, 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; while,
REST is completely stateless.
 SOAP applies message format like XML; while, REST does not apply
message formats like XML or JSON.
 To expose the service, SOAP uses interfaces and named operations; while
REST uses URI and methods like POST, GET, PUT, DELETE for exposing
resources (service).

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.

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.

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.
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.

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.

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.

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.

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:
1 $.get(“/api/Employees/1”, null, function(response) {

2 $(“#employees”).html(response);

3 });

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:

1 [HttpGet]

2 public void GetEmployee(int id)

3{

4 StudentRepository.Get(id);

5}

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

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:

1 public void GetEmployee(int id)

2{

3 StudentRepository.Get(id);

4}

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

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

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
}

How to navigate another page in jQuery?

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

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.

How to mention Roles and users using Authorize attribute in Web


API?

A: // Restrict by Name

[Authorize(Users=”Shiva,Jai”)]
public class StudentController : ApiController

// Restrict by Role

[Authorize(Roles=”Administrators”)]
public class StudnetController : ApiController

Can we apply constraints at the route level?


A: Yes, it can be applied.

[Route(“students/{id:int}”]
public User GetStudentById(int id) { … }

[Route(“students/{name}”]
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.

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

config.MapHttpAttributeRoutes();

// Other Web API configuration not shown.

How parameters get the value in Web API?

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

 Request body
 URI
 Custom Binding

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

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

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.

Where is the route defined in Web API?

A: It is placed in the App_Start directory.

App_Start –> WebApiConfig.cs

routes.MapHttpRoute(

name: “myroute”,

routeTemplate: “api/{controller}/{id}”,

defaults: new { id = RouteParameter.Optional }

);

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;

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.

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.
What is the namespace for IHttpActionResult return type in Web
API?

A: System.Web.Http.Results namespace

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. 

Which .NET framework supports Web API?


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

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. 

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

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. 

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. 
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. 

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.

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

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 –

1public IHttpActionResult GetProductMaster(int id) { ProductMaster productMaster = db.ProductMas


Ok(productMaster); } In the same way, the Post method will require complex type parameters to p
productMaster) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.ProductMasters.
productMaster.id }, productMaster); } Similarly PUT method will require primitive data type exa
productMaster.id) { return BadRequest(); }  db.Entry(productMaster).State = EntityState.Modifie
ProductMasterExists(id)) { return NotFound(); } else { throw; } }

Give an example to specify Web API Routing. 

Here is an example of Web API routing –

Config.Routes.MapHttpRoute(   name: "MyRoute,"//route name   routeTemplate: "api/{controller}/{


1RouteParameter.Optional }   );

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());  

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. 

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 
Explain the code snippet to show how we can return 404 errors
from HttpError.

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

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

What is the code used to register an exception filter from the


action?

One can register an exception filter using the following code –

1 [NotImplExceptionFilter]  public TestCust GetMyTestCust (int custno)  {  //write the code 

What are the testing tools or API for developing or testing web
API?
 CFX
 Axis
 Jersey API 
 Restlet 

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. 

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


ArrayList paramList = new ArrayList();  Category c = new Category { CategoryId = 1, CategoryNam
1Price = 15500, CategoryID = 1 };  paramList.Add(c);  paramList.Add(p);

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. 

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. 

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 

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. 

Name method that validates all controls on a page?

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

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.

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

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. 

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.  

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. 

What is the difference between ApiController and Controller?

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

1public class TweetsController : ApiController {          // GET: /Api/Tweets/           public

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

public class TweetsController : Controller  {           // GET: /Tweets/  [HttpGet]  public Act
1JsonRequestBehavior.AllowGet);          } }

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. 

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 

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”;

You might also like