Introduction
The process by which a browser or other client caches a server's response is known as response caching. This will facilitate the prompt processing of subsequent requests for the same resources. Furthermore, the server won't have to process and produce the same response repeatedly thanks to this.
The response caching headers are set by ASP.NET Core using the ResponseCache attribute. Additionally, we can manage the caching behavior from the server side by utilizing the Response Caching Middleware. Clients and other proxies can read the response caching headers once we've set them up to figure out how to cache the server response. Caching headers are required for browsers, clients, and proxies in accordance with the HTTP 1.1 Response Cache Specification.
What is meant by caching?
Caching is a method of temporarily storing data that is frequently accessed so that it can be quickly retrieved. As a result, there will be less need to repeatedly retrieve the same data from the database or other storage devices, which will enhance the application's overall performance.
ASP.NET Core Caching Types
Multiple Caching Mechanism Types are Supported by ASP.NET Core. They are listed in the following order.
- In-Memory Caching: The most basic type of caching, in-memory caching works well with a single server. The main memory of the web server houses the data. It is quick and appropriate for data that doesn't require persistence past the web server process' lifetime or require a lot of memory. It works well for storing modest volumes of information.
- Distributed Caching: Applications that must share data across multiple servers in load-balancing or multi-server environments are best suited for distributed caching. It entails keeping data in an external system, like NCache, SQL Server, Redis, and so forth. Although it requires more work than in-memory caching, large-scale applications must use it to guarantee consistency between requests and sessions.
- Response Caching: Response Caching is the process of keeping the result of a request-response cycle in the cache in order to serve the resource from the cache in response to subsequent requests rather than having to generate the response from scratch. This method can greatly enhance the performance of a web application, particularly for resources that are costly to produce and don't change frequently.
HTTP Based Response Caching
Let's now discuss the various HTTP Cache Directives and how to use them to regulate the behavior of caching.
The main header field that we use to indicate how a response can be cached is cache-control. Clients, proxy servers, and browsers should respect and abide by the cache-control header when it appears in the response.
Let's now examine the standard cache-control directives.
- public: denotes the ability for a cache to hold the response locally on the client or in a shared location.
- private: denotes that the response may only be stored in a client-side private cache and not in a shared cache.
- no-cache: The no-cache flag instructs a cache not to respond to any requests with a stored response.
- no-store: The no-store flag instructs a cache not to keep the answer.
Although no-cache and no-store have similar sounds and even actions, browsers and clients interpret them differently. As we work through the examples, we will go into further detail about this.
A few more headers, in addition to cache control, can regulate the caching behavior.
For backward compatibility with the no-cache directive and the HTTP 1.0 specification, the pragma header is used. It will disregard the pragma header if we supply the cache-control header.
Vary: This tells it that it can only send a cached response if every field in the header precisely matches the request that came in before. A new response is generated by the server if any of the fields are modified.
Illustrations of HTTP Cache Directives
We will now create an ASP.NET Core application to demonstrate how the cache directives work. Now let's add a controller action method to an ASP.NET Core Web API project that has been created.
public record EmployeeDto
{
public Guid Id { get; init; }
public string Name { get; init; }
public EmployeeType Type { get; init; }
public string Mno { get; init; }
public decimal Salary { get; init; }
public DateTime CurrentDate { get; init; } = DateTime.Now;
}
[HttpGet("{id}")]
public IActionResult GetById(Guid id)
{
var emp = _employeeService.GetById(id);
if (emp == null)
{
return NotFound();
}
return Ok(emp);
}
We can see that this endpoint response adds the real date and time of execution to the response each time it is called. We are going to update the endpoint with response caching now.
Important note. We should always click links on the page or use Swagger to launch the API endpoints in the browser when testing response caching. Otherwise, regardless of the response cache settings, the browser will always request a fresh response from the server if we try to refresh the page or invoke the URI again.

ResponseCache Attribute
The ResponseCache attribute for an ASP.NET Core application specifies the properties for configuring the relevant response caching headers. This attribute can be used for specific endpoints or at the controller level.
Let's update the API endpoint with the ResponseCache attribute.
[HttpGet("{id}")]
[ResponseCache(Duration = 120, Location = ResponseCacheLocation.Any)]
public IActionResult GetById(Guid id)
{
var emp = _employeeService.GetById(id);
if (emp == null)
{
return NotFound();
}
return Ok(emp);
}








mina shakerPosted Sep 9, 2024, 8:49 PM
Thank you very mush