🔐 ASP.NET Security, Performance & Caching
Estimated reading: 4 minutes 43 views

⚡ ASP.NET – Data Caching – Boost Performance with Smart Caching Techniques

🧲 Introduction – Why Use Data Caching in ASP.NET?

Web applications often deal with repetitive database calls or expensive computations. Data caching in ASP.NET is a powerful technique to store data temporarily in memory so that future requests can be served faster and more efficiently.

🎯 In this guide, you’ll learn:

  • What caching is and how it works in ASP.NET
  • Different types of caching: Output, Data, and Object
  • How to implement data caching with code examples
  • Common use cases and performance tips

💡 What Is Caching?

Caching is a mechanism to store frequently accessed data in memory for quick retrieval. Instead of fetching data from the database every time, ASP.NET can serve cached data until it expires or is explicitly removed.


🚀 Types of Caching in ASP.NET

ASP.NET supports three major types of caching:

🧱 Type🔍 Description
Output CachingStores the final HTML of a page
Data CachingStores custom objects or data (e.g., DataTables)
Object CachingStores any .NET object in memory via the Cache object

🧰 Output Caching

Output Caching stores the entire rendered page or control, allowing ASP.NET to bypass page processing.

<%@ OutputCache Duration="60" VaryByParam="None" %>

🔍 Explanation:

  • Duration="60": Cache output for 60 seconds
  • VaryByParam="None": Output is not varied by query parameters

🧪 Effect: ASP.NET returns the cached page output without re-running server-side code.


📦 Data Caching with Cache Object

Use the HttpContext.Cache or System.Web.Caching.Cache object to store data manually.

// Caching a DataTable for 5 minutes
DataTable dt = GetDataFromDatabase();
Cache.Insert("EmployeeData", dt, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero);

🔍 Explanation:

  • "EmployeeData" is the key to identify cached data
  • DateTime.Now.AddMinutes(5): Absolute expiration in 5 minutes
  • TimeSpan.Zero: No sliding expiration
// Retrieving cached data
DataTable cachedData = (DataTable)Cache["EmployeeData"];
if (cachedData != null)
{
    GridView1.DataSource = cachedData;
    GridView1.DataBind();
}

🧪 Output:
Cached data is loaded into a GridView instantly without hitting the database.


🧠 Object Caching with Priority and Dependency

You can cache any object and control when and how it’s removed using CacheDependency or CacheItemPriority.

string data = "Cached message for dashboard.";
Cache.Insert("DashboardNote", data, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero,
             CacheItemPriority.High, null);

🔍 Explanation:

  • Stores a simple string with high priority
  • Automatically expires after 30 seconds
string cachedNote = Cache["DashboardNote"] as string;
lblMessage.Text = cachedNote;

🧪 Output:
Label displays the cached message if available.


🔁 Cache Dependency Example

CacheDependency dep = new CacheDependency(Server.MapPath("mydata.xml"));
Cache.Insert("XmlBasedData", obj, dep);

🔍 Explanation:

  • Cache entry is removed when mydata.xml changes
  • Useful when cache should reflect external file changes

📘 Best Practices for Data Caching

✅ Use caching for:

  • Reusable DB queries
  • Common dropdown values
  • Static reports

⚠️ Avoid caching:

  • Sensitive or user-specific data globally
  • Very large objects without eviction strategy

📌 Summary – Recap & Next Steps

Caching in ASP.NET is an essential technique to enhance performance, reduce server load, and improve user experience. Whether it’s output, data, or object caching, choosing the right type and strategy is crucial.

🔍 Key Takeaways:

  • OutputCache is best for static pages
  • Cache.Insert allows full control over object caching
  • Use expiration, priority, and dependency to manage cache effectively

⚙️ Real-world Use Cases:

  • Dashboard widgets
  • Static lookups (e.g., country/state lists)
  • Frequently used API responses

❓ FAQs – Data Caching in ASP.NET


How do I remove an item from cache manually?
✅ Use Cache.Remove("KeyName") to delete a specific item.

Cache.Remove("EmployeeData");

💬 Removes the cached DataTable so it can be regenerated on the next request.


Can I cache different versions of the same page?
✅ Yes, use VaryByParam in Output Caching.

<%@ OutputCache Duration="60" VaryByParam="category" %>

💬 Different output will be cached for each query string value of category.


What is sliding expiration in object caching?
✅ It resets the expiration timer every time the item is accessed.

Cache.Insert("userData", data, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10));

💬 Item expires only if not accessed for 10 minutes.


How to cache large datasets securely?
✅ Serialize and compress large objects; avoid caching sensitive info globally.

string jsonData = JsonConvert.SerializeObject(largeData);
Cache["BigData"] = jsonData;

💬 Caches as compressed JSON string instead of bulky objects.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

⚡ ASP.NET – Data Caching

Or Copy Link

CONTENTS
Scroll to Top