---
title: "使用Cache缓存Page页面 (转)"
author: "dzgwt2004"
date: "2008-10-12T10:42:31Z"
tags: []
slug: "cache-page"
draft: false
lastmod: "2008-10-12T10:42:31Z"
id: 251772
url: "https://digga2012.iteye.com/blog/251772"
---

使用Cache：
<%@ OutputCache Duration="15" VaryByPara="None" %>
页面使用Cache，Cache的有效期为15 seconds

使用代码表示，放在Page_Load里面：

```C#
//
//Cache Manager可以控制这个页面
//
Response.Cache.SetCacheability(HttpCacheability.Public);
```


```C#
//
//告诉Cache Manager，页面的有效期为当前时间+15秒
//
Response.Cache.SetExpires(DateTime.Now.AddSeconds(15));
```


当使用@OutputCache时，Asp.Net 调用页面对象的InitOutPutCache()，将Cache转换为对应的HttpCachePolicy（）。

所有对此页面的请求，都是访问Cache中的信息，直到Cache的生存周期结束。

对于页面的Cache的使用范围和存储位置：
Cache的使用范围可以使用Location属性，或者HttpResponse.Cache对象来设置。
<%@ OutputCache Duration="15" Location="Client" VaryByPara="None" %>
或者

```C#
Response.Cache.SetExpires(DateTime.Now.AddSeconds(15));
Response.Cache.SetCacheability(HttpCacheabiligy.Private);
```



默认状况下，Cache可以存放在任意位置，如：用户的浏览器，响应的服务器，或者代理服务器
<%@ OutputCache Duration="15" Location="Any" VaryByPara="None" %>
等效于：

```C#
Response.Cache.SetExpires(DateTime.Now.AddSeconds(15));
Response.Cache.SetCacheability(HttpCacheability.Public);
```



如果禁止Cache，那么可以：
<%@ OutputCache Location="None" VaryByPara="None" %>
等效于：

```C#
Response.Cache.SetCacheability(HttpCacheability.NoCache);
```



使Cache存在于响应的服务器：
<%@ OutputCache Duration="15" Location="Server" VaryByPara="None" %>
等效于：

```C#
Response.Cache.SetExpires(DateTime.Now.AddSeconds(15));
Response.Cache.SetCacheability(HttpCacheability.Server);
```



使Cache存在于Client：
<%@ OutputCache Duration="15" Location="Any" VaryByParam="Client" %>
等效于：

```C#
Response.Cache.SetExpires(DateTime.Now.AddSeconds(15));
Response.Cache.SetCacheability(HttpCacheability.Private);
```



如果使用了集群，那么对于Cache的控制，应该由代理服务器来完成：
<%@ OutputCache Duration="15" Localtion="Location" VaryByPara="Client" %>
等效于：

```C#
Response.Cache.SetExpires(DateTime.Now.AddSeconds(15));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetNoServerCaching();
```


注意：使用Location属性，不能保证任何页面的用户控件都使用定义的Location位置，同样：如果禁止使用Cache，也不能保证页面的用户控件都禁用了Cache。 


http://support.microsoft.com/kb/323290