WebRequest.DefaultCachePolicy Property

Definition

Gets or sets the default cache policy for this request.

C#
public static System.Net.Cache.RequestCachePolicy? DefaultCachePolicy { get; set; }
C#
public static System.Net.Cache.RequestCachePolicy DefaultCachePolicy { get; set; }

Property Value

A HttpRequestCachePolicy that specifies the cache policy in effect for this request when no other policy is applicable.

Examples

The following code example demonstrates setting the default cache policy for Web requests.

C#
        public static WebResponse GetResponseFromServer2(Uri uri)
{
     RequestCachePolicy policy =
        new  RequestCachePolicy( RequestCacheLevel.NoCacheNoStore);
    WebRequest request = WebRequest.Create(uri);
    WebRequest.DefaultCachePolicy = policy;
    WebResponse response = request.GetResponse();
    Console.WriteLine("Policy is {0}.", policy.ToString());
    Console.WriteLine("Is the response from the cache? {0}", response.IsFromCache);
    return response;
}

Remarks

Caution

WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete, and you shouldn't use them for new development. Use HttpClient instead.

This policy is used for this request if the following conditions exist:

  • There is no DefaultCachePolicy property specified for this request.

  • The machine and application configuration files do not specify a cache policy that is applicable to the Uniform Resource Identifier (URI) used to create this request.

The cache policy determines whether the requested resource can be taken from a cache instead of sending the request to the resource host computer.

A copy of a resource is only added to the cache if the response stream for the resource is retrieved and read to the end of the stream. So another request for the same resource could use a cached copy, depending on the cache policy level for this request.

Applies to

Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

See also