WebRequest.CachePolicy 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得或設定這個要求的快取原則。
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;
}
備註
謹慎
WebRequest
、HttpWebRequest
、ServicePoint
和 WebClient
已經過時,您不應該將它們用於新的開發。 請改用 HttpClient。
目前快取原則和快取中要求的資源是否存在,會判斷是否可以從快取擷取回應。 使用快取的回應通常可改善應用程式效能,但快取中的回應與伺服器上的回應不符的風險。
您可以在 Machine.config 組態檔中指定預設快取原則,或為使用超文本傳輸通訊協定 (HTTP) 或安全超文本傳輸通訊協定 (HTTPS) URI 配置的要求設定 DefaultCachePolicy 屬性。
只有在擷取資源響應數據流並讀取至數據流結尾時,才會將資源的複本新增至快取。 因此,相同資源的另一個要求可以使用快取的複本,視此要求的快取原則層級而定。