2011-04-14 117 views
1

當我在action方法上使用outputcaching時,它被完整的url緩存,我想要做的是緩存頁面,但忽略url的某些部分。在Global.asax中定義使用Outputcache忽略url值

定製路線:

routes.MapRoute(
    "Template", 
    "Report/{reportid}/{reportname}/Template/{templateid}/{action}", 
    new { controller = "Template", action = "Index" } 
); 

我的模板控制器

public class TemplateController : Controller 
{ 
    [OutputCache(Duration=60*60*2)] 
    public ActionResult Index(Template template) 
    { 
     /* some code */ 
    } 
} 

例如,當我去到以下網址:

http://mywebsite.com/Report/789/cacheme/Template/5
- >緩存根據網址提供2小時

http://mywebsite.com/Report/777/anothercacheme/Template/5
- >也被緩存基於該URL2小時

我想的是,的OutputCache忽略REPORTNAME和reportid值所以,當我去到上述網址的則返回相同緩存版本。這是可能的OutputCache屬性或將我必須編寫我的自定義OutputCache FilterAttribute?

+0

也許,方式之一可能是使REPORTNAME,reportid作爲參數的方法,然後用'VaryByParam'只templateid。除此之外,自定義篩選器屬性將成爲您的選擇! – VinayC 2011-04-14 08:40:05

+0

我試過了,但它仍然會爲請求的模板返回不同的緩存版本 – 2011-04-14 10:06:48

回答

1

結束了與以下(按http://blog.stevensanderson.com/2008/10/15/partial-output-caching-in-aspnet-mvc/啓發):

public class ResultCacheAttribute : ActionFilterAttribute 
    { 
     public ResultCacheAttribute() 
     { 

     } 

     public string CacheKey 
     { 
      get; 
      private set; 
     } 

     public bool AddUserCacheKey { get; set; } 
     public bool IgnoreReport { get; set; } 

     /// <summary> 
     /// Duration in seconds of the cached values before expiring. 
     /// </summary> 
     public int Duration 
     { 
      get; 
      set; 
     } 

     public override void OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      string url = ""; 
      foreach (var item in filterContext.RouteData.Values) 
      { 
       if (IgnoreReport) 
        if (item.Key == "reportid" || item.Key == "reportname") 
         continue; 

       url += "." + item.Value; 
      } 
      if (AddUserCacheKey) 
       url += "." + filterContext.HttpContext.User.Identity.Name; 

      this.CacheKey = "ResultCache-" + url; 

      if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) 
       this.CacheKey += "-ajax"; 

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

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

      base.OnActionExecuted(filterContext); 
     } 
    }