Export (0) Print
Expand All

How to: Set Cache Policy for a Request

The following example demonstrates setting a cache policy for a request. The example input is a URI such as http://www.contoso.com/.

The following code example creates a cache policy that allows the requested resource to be used from the cache if it has not been in the cache for longer than one day. The example displays a message that indicates whether the resource was used from the cache—for example, "The response was retrieved from the cache : False."—and then displays the resource. A request can be fulfilled by any cache between the client and server.

using System;
using System.Net;
using System.Net.Cache;
using System.IO;

namespace Examples.System.Net.Cache
{
    public class CacheExample
    {   
        public static void UseCacheForOneDay(Uri resource)
        {
            // Create a policy that allows items in the cache
            // to be used if they have been cached one day or less.
            HttpRequestCachePolicy requestPolicy = 
                new HttpRequestCachePolicy (HttpCacheAgeControl.MaxAge,
                TimeSpan.FromDays(1));
            
            WebRequest request = WebRequest.Create (resource);
            // Set the policy for this request only.
            request.CachePolicy = requestPolicy;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Determine whether the response was retrieved from the cache.
            Console.WriteLine ("The response was retrieved from the cache : {0}.",
               response.IsFromCache);
            Stream s = response.GetResponseStream ();
            StreamReader reader = new StreamReader (s);
            // Display the requested resource.
            Console.WriteLine(reader.ReadToEnd());
            reader.Close ();
            s.Close();
            response.Close();
        }
        public static void Main(string[] args)
        {
            if (args == null || args.Length != 1)
            {
                Console.WriteLine ("You must specify the URI to retrieve.");
                return;
            }
            UseCacheForOneDay (new Uri(args[0]));
        }
    }
}

Community Additions

ADD
Show:
© 2014 Microsoft