views:

197

answers:

0

hi, I want to cache the ActionResult object that returns by a controller in asp.net mvc. So i created a ActionFilterAttribute subclass named ResultCacheAttribute that uses the HttpContext.Cache as the cache provider. The cache worked but it also alters the processing flow: now the view engine CreateView method won't be executed, instead it renders the view in previous controller's call.

Here is my ResultCacheAttribute class

public class ResultCacheAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
 string url = filterContext.HttpContext.Request.Url.PathAndQuery;
 CacheKey = "ResultCache-" + url;

 if (filterContext.HttpContext.Cache[CacheKey] != null)
 {
   filterContext.Result = (ActionResult)filterContext.HttpContext.Cache[CacheKey];
 }
 base.OnActionExecuting(filterContext);
}

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
 filterContext.Controller.ViewData["CachedStamp"] = DateTime.Now;
 filterContext.HttpContext.Cache.Add(CacheKey, filterContext.Result, Dependency, DateTime.Now.AddSeconds(Duration),  System.Web.Caching.Cache.NoSlidingExpiration, Priority, null);

 base.OnActionExecuted(filterContext);
}