ASP.NET MVC 结果缓存






3.67/5 (9投票s)
使用 ActionFilter 缓存 ActionResult
引言
这种缓存方法的思想很简单:Web 应用程序应该缓存需要大量 CPU/数据库时间来加载的 ActionResults。目前,ASP.NET MVC 框架有一个缓存功能,即 OutputCache
,它通过存储结果网页的副本来工作。此功能不适用于网页依赖于例如会话数据的场景。
Using the Code
将 ResultCache
属性添加到控制器的某个 Action。
[ResultCache(Duration=60)]
public ActionResult About()
{
//code that demands heavy CPU/DB time to execute
//...
ViewData["DummyData"] = dummy;
return View();
}
以下是 ViewPage
代码
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<h2>About</h2>
<p>
Sample ViewData value: <%=ViewData["DummyData"]%>
</p>
<p>
Sample Session dependant data <%=Session["UserName"] %>
</p>
使用 ResultCache
不会影响 ViewPage
中的代码。在示例中,View 显示来自 ViewData
(可以缓存)和 Session
的数据。
工作原理
Action 执行后,Action Filter 会将 ActionResult
存储在应用程序缓存中。
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
//Add the ActionResult to cache
filterContext.HttpContext.Cache.Add(this.CacheKey, filterContext.Result,
Dependency, DateTime.Now.AddSeconds(Duration),
System.Web.Caching.Cache.NoSlidingExpiration, Priority, null);
//Add a value in order to know the last time it was cached.
filterContext.Controller.ViewData["CachedStamp"] = DateTime.Now;
base.OnActionExecuted(filterContext);
}
下次调用 Action 时,该属性将从缓存中检索结果,从而防止 Action 执行。
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string url = filterContext.HttpContext.Request.Url.PathAndQuery;
this.CacheKey = "ResultCache-" + url;
if (filterContext.HttpContext.Cache[this.CacheKey] != null)
{
//Setting the result prevents the action itself to be executed
filterContext.Result =
(ActionResult)filterContext.HttpContext.Cache[this.CacheKey];
}
base.OnActionExecuting(filterContext);
}
关于代码
这种缓存方法在开源 MVC 站点 prsync.com 中使用。
在 CodePlex 上获取该站点的完整源代码。
历史
- 2009年2月16日 - 提交文章
- 2009年2月17日 - 改进代码注释