WebRequest.CachePolicy 属性

定义

获取或设置此请求的缓存策略。

public:
 virtual property System::Net::Cache::RequestCachePolicy ^ CachePolicy { System::Net::Cache::RequestCachePolicy ^ get(); void set(System::Net::Cache::RequestCachePolicy ^ value); };
public virtual System.Net.Cache.RequestCachePolicy? CachePolicy { get; set; }
public virtual System.Net.Cache.RequestCachePolicy CachePolicy { get; set; }
member this.CachePolicy : System.Net.Cache.RequestCachePolicy with get, set
Public Overridable Property CachePolicy As RequestCachePolicy

属性值

定义缓存策略的 RequestCachePolicy 对象。

示例

下面的代码示例演示如何设置 Web 请求的缓存策略。

// The following method demonstrates overriding the
// caching policy for a request.
static WebResponse^ GetResponseNoCache( Uri^ uri )
{
   // Set a default policy level for the "http:" and "https" schemes.
   HttpRequestCachePolicy^ policy = gcnew HttpRequestCachePolicy( HttpRequestCacheLevel::Default );
   HttpWebRequest::DefaultCachePolicy = policy;

   // Create the request.
   WebRequest^ request = WebRequest::Create( uri );

   // Define a cache policy for this request only. 
   HttpRequestCachePolicy^ noCachePolicy = gcnew HttpRequestCachePolicy( HttpRequestCacheLevel::NoCacheNoStore );
   request->CachePolicy = noCachePolicy;
   WebResponse^ response = request->GetResponse();
   Console::WriteLine( L"IsFromCache? {0}", response->IsFromCache );
   
   return response;
}
// The following method demonstrates overriding the
// caching policy for a request.
public static WebResponse GetResponseNoCache(Uri uri)
{
    // Set a default policy level for the "http:" and "https" schemes.
    HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
    HttpWebRequest.DefaultCachePolicy = policy;
    // Create the request.
    WebRequest request = WebRequest.Create(uri);
    // Define a cache policy for this request only.
    HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
    request.CachePolicy = noCachePolicy;
    WebResponse response = request.GetResponse();
    Console.WriteLine("IsFromCache? {0}", response.IsFromCache);
    return response;
}

注解

当前缓存策略和缓存中是否存在请求的资源决定了是否可以从缓存中检索响应。 使用缓存的响应通常会提高应用程序性能,但存在缓存中的响应与服务器上的响应不匹配的风险。

可以在 Machine.config 配置文件中指定默认缓存策略,或者为使用超文本传输协议 (HTTP) 或安全超文本传输协议 (HTTPS) URI 方案的请求设置 DefaultCachePolicy 属性。

仅当检索到资源的响应流并将其读取到流的末尾时,才会将资源的副本添加到缓存中。 因此,针对同一资源的另一个请求可以使用缓存副本,具体取决于此请求的缓存策略级别。

适用于

另请参阅