
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
824
|
Chapter 14: Web
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");
}
Discussion
The 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 ...