Recipe 14.17. Using Cached Results When Working with HTTP for Faster PerformanceProblemYou are looking for a way to speed up code that reaches out to the Web via HTTP for content. SolutionUse the RequestCachePolicy class to determine how your HttpWebRequests react in the presence of a caching entity. RequestCachePolicy has seven levels defined by the RequestCacheLevel enumeration, as shown in Table 14-3.
The RequestCachePolicy is set up using the CacheIfAvailable RequestCacheLevel so that the request will always take the "closest" content to enhance retrieval speed. If Default is used, the request is still subject to the underlying cache policy of the system, and that can prevent the use of intermediate caches. To assign the cache policy, set the CachePolicy property on the HttpWebRequest to the newly created RequestCachePolicy. Once the policy is in place, get the response. The HttpWebResponse object has a property called IsFromCache that tells if the response came from a cache. string html = ""; string url = "http://www.oreilly.com"; // Set up the request (Recipe 14.6 has GenerateHttpWebRequest). HttpWebRequest request = GenerateHttpWebRequest(url); // Make a cache policy to use cached results if available. // The default is to bypass the cache in machine.config. RequestCachePolicy rcpCheckCache = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable); // Assign the new policy to the request. request.CachePolicy = rcpCheckCache; // Execute the request. HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException we) { Console.WriteLine(we.ToString()); } // Check if we hit the cache. if(response.IsFromCache==false) { Console.WriteLine("Didn't hit the cache"); } DiscussionThe default request cache policy for an appdomain can be set by using the HttpWebRequest.DefaultCachePolicy property. The CachePolicy property shown in the solution sets the policy for a particular request. The default caching policy is specified in the machine.config file in the system.net/requestCaching element as shown here: <requestCaching defaultPolicyLevel="BypassCache" isPrivateCache="true" unspecifiedMaximumAge="1.00:00:00" > See AlsoSee the "RequestCachePolicy Class," "RequestCacheLevel Enumeration," and "Default-CachePolicy Property" topics in the MSDN documentation. |