2010-11-24 14 views
1

ASP.NET MVC3 RC1でアクションメソッドの呼び出しをキャッシュしようとしました。Html.Actionへの呼び出しのキャッシュ

キャッシングは機能しますが、パラメータによるバリエーションはうまくいかないようです。 HotOffersへの3回の呼び出しがproductIDに応じて異なる結果を返すために私ができることはありますか?

出力は今

ホット申し出4

ホット申し出4つの

ホット申し出4

私は出力が

ホット申し出4

になりたいです

オファーを提示6

ホット申し出8

アクション

[OutputCache(Duration = 100, VaryByParam = "productId")] 
public PartialViewResult HotOffers(int productId) 
{ 
    ProductModel model = new ProductModel { ProductID = productId }; 
    model.Name = "Meatball"; 

    return PartialView(model); 
} 

ページ(Index.cshtml)

@{ 
    View.Title = "Home Page"; 
} 
<p> 
<div> 
    @Html.Action("HotOffers", new { productid=4}) 
</div> 
<div> 
@Html.Action("HotOffers", new { productid=6}) 
</div> 
<div> 
@Html.Action("HotOffers", new { productid = 8 }) 
</div> 
</p> 

部分(HotOffers.cshtml)

Hot offers 
@Model.ProductID 
+1

の修正だった

public class ActionOutputCacheAttribute : ActionFilterAttribute { public ActionOutputCacheAttribute(int cacheDuration) { this.cacheDuration = cacheDuration; } private int cacheDuration; private string cacheKey; public override void OnActionExecuting(ActionExecutingContext filterContext) { string url = filterContext.HttpContext.Request.Url.PathAndQuery; this.cacheKey = ComputeCacheKey(filterContext); 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); } public override void OnActionExecuted(ActionExecutedContext filterContext) { //Add the ActionResult to cache filterContext.HttpContext.Cache.Add(this.cacheKey, filterContext.Result,null, DateTime.Now.AddSeconds(cacheDuration), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); //Add a value in order to know the last time it was cached. filterContext.Controller.ViewData["CachedStamp"] = DateTime.Now; base.OnActionExecuted(filterContext); } private string ComputeCacheKey(ActionExecutingContext filterContext) { var keyBuilder = new StringBuilder(); keyBuilder.Append(filterContext.ActionDescriptor.ControllerDescriptor.ControllerName); keyBuilder.Append(filterContext.ActionDescriptor.ActionName); foreach (var pair in filterContext.RouteData.Values) { if(pair.Value != null) keyBuilder.AppendFormat("rd{0}_{1}_", pair.Key.GetHashCode(), pair.Value.GetHashCode()); } return keyBuilder.ToString(); } } 

を無視します。修正はすでに製品にチェックインされており、次のリリースで利用可能になるはずです。 – Levi

答えて

1

asp.netで使用されるキャッシングシステムはMVCの外に存在するため、Urlsにのみ適用され、VaryByParamはQueryStringパラメータにのみ適用されます。

私はいくつかのコードOutputCache behavior in ASP.NET MVC 3を掲示しました。それはあなたがパラメータに基づいてアクションをキャッシュするようになるはずです。その特定の例では、実際にはルートフィールドの1つを無視する「無視」パラメータを追加しましたが、削除するだけでOKです。私はここのsansそれを投稿することができますね

は、上記のコードは、これはMVC 3 RCにおける機能の間違った設計によるものですhttp://blog.stevensanderson.com/2008/10/15/partial-output-caching-in-aspnet-mvc/

関連する問題