您的位置:首页 > 编程语言 > ASP

ASP.NET MVC 3 使用页面缓存 OutputCache 需要注意的问题

2015-04-28 17:38 761 查看
项目使用MVC3框架,页面使用缓存来缓解服务器压力,使用缓存配置文件设置CacheProfile

<system.web>
...........<!--其他配置节点-->
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="index" duration="20" enabled="true" location="Client" varyByParam="city,type"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>


在Action上使用OutputCache特性

[OutputCache(CacheProfile="index")]
public ActionResult Index(string city, string type)
{

ViewBag.City = city;
ViewBag.Type = type;
ViewBag.Message = "欢迎使用 ASP.NET MVC!";
var queryList = list.Where(c => c.City == city);
return View(queryList);
}


配置和代码完成以后,运行页面。首次页面返回200状态,按 F5后页面还是返回200的状态码,怎么回事呢,页面居然没有被缓存。。。。

原来这是ASP.NET的一个BUG,如何解决呢?我们可以在Action方法内加 Response.Cache.SetOmitVaryStar(true);这段代码。测试发现配置信息里的属性location配置为"Client"时,缓存并没有生效,页面还是无法被缓存。。。。这个太坑了吧。

将配置信息里的属性location配置为"ServerAndClient"时,页面才能被缓存。

<system.web>
...........<!--其他配置节点-->
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="index" duration="20" enabled="true" location="ServerAndClient" varyByParam="city,type"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>


public ActionResult Index(string city, string type)
{
Response.Cache.SetOmitVaryStar(true);
ViewBag.City = city;
ViewBag.Type = type;
ViewBag.Message = "欢迎使用 ASP.NET MVC!";
var queryList = list.Where(c => c.City == city);
return View(queryList);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: