WebCache Class

Provides a cache to store frequently accessed data.

System.Object
  System.Web.Helpers.WebCache

Namespace:  System.Web.Helpers
Assembly:  System.Web.Helpers (in System.Web.Helpers.dll)

public static class WebCache

The WebCache type exposes the following members.

  NameDescription
Public methodStatic memberGetRetrieves the specified item from the WebCache object.
Public methodStatic memberRemoveRemoves the specified item from the WebCache object.
Public methodStatic memberSetInserts an item into the WebCache object.
Top

This class represents a helper, which is a component that simplifies web programming in ASP.NET Web Pages. Use the WebCache class to cache frequently accessed data, which can improve website performance. Information that is often accessed but rarely changed is a good candidate for caching. For example, you might cache a list of phone area codes or postal codes. Or you might cache weather forecast information that is unique to the region of a user, and then update the cached forecast data at set intervals. In a web page, you can retrieve cached items instead of fetching the information again from its source each time the page is requested. The data that you add to the cache can be any type of object, including complex, nested data objects that are returned from database queries, arrays of values, or simple objects such as a number, a time stamp, or a string.

Items that you put into the cache are removed automatically. Typically, you specify a timeout as an interval (by default, 20 minutes) after which the item expires and is no longer cached. However, items can also be removed before the timeout period if the server runs low on memory or for other reasons. (For example, the web server is restarted, the cache is cleared.) In general, you should never count on an item that you have cached to be in the cache; when you get an item out of the cache, make sure you have actually gotten the item and not null. If necessary, re-fetch the item and put it into the cache again.

You can use the following WebCache class methods to create, retrieve, and remove data from the cache:

The following example shows how to use methods of the WebCache class to cache data.


@{   
    // On each request, use WebCache.Get to check whether the cache item exists.
    if(WebCache.Get("postalCodes") == null) {
        // Call the helper method to create the cache item if needed.
        @AddPostalCodesToToCache();
    }

    // If the request is a postback, the user submitted a cache update.
    // Users choose to reset the default list, or add a custom postal code.
    if(IsPost) {
        // If user chose reset, then remove and recreate the cache item.
         if(Request["UpdateType"] == "reset") {
            WebCache.Remove("postalCodes");
            // Call the helper to recreate the cache with default postal codes.
            @AddPostalCodesToToCache();
        }
        else {
            // If user chose add, then add a custom value to update the cache. 
            // First retrieve the existing values. Use a generic 
            // List to make it easy to add a new value to the list.
            List<string> customPostalData = new List<string>(WebCache.Get("postalCodes"));
            // Add the value submitted by a user. 
            customPostalData.Add(Request["NewCode"]);
            // Call the method to update the cache, and pass a list with the new postal code.
            @AddPostalCodesToToCache(customPostalData);
        }       
    } 

}

@helper AddPostalCodesToToCache(object postalCodeData = null) {
    // If the postalCodeData param is null, no custom postal code 
    // values were submitted, so use the default postal code list.
    if(postalCodeData == null) {
        // Create cache data from an array. Data for the 
        // cache can also come from a database or other sources.
        string[] postalCodeArray = {"123456", "234567", "345678"};
        postalCodeData = postalCodeArray;
    }
    // Create the postal codes cache item.
    WebCache.Set("postalCodes", postalCodeData, 1000, false);
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>WebCache Helper</title>
    </head>
    <body>
        <form method="post" action="">
            <input type="radio" name="UpdateType" value="reset" />Reset the original postal codes list<br />
            <input type="radio" name="UpdateType" value="add" checked />Add a custom postal code <br />
            <div style="margin-left: 35px">
              <label for="NewCode">New Code: </label>
              <input name="NewCode" type="text" value="" />
            </div>
            <p></p>
            <input name="UpdateCache" type="Submit" value="Update Postal Codes" />
	</form>
        <h2>Postal Code Listing</h2>
        <div>
            <!-- Loop through and display the postal codes from the cache. -->
            @foreach (string p in WebCache.Get("postalCodes")) {
                <p>@p</p>
	    }
        </div>
    </body>
</html>


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show: