2012-06-25 57 views
1

我有一個類我模型綁定,我想使用輸出緩存。我不能找到一種方法來訪問綁定對象GetVaryByCustomStringVaryByCustom和模型綁定

例如:

public class MyClass 
{ 
    public string Id { get; set; } 
    ... More properties here 
} 

public class MyClassModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var model = new MyClass(); 
     ... build the class  
     return model; 
    } 
} 

我設置的粘結劑Global.cs

ModelBinders.Binders.Add(typeof(MyClass), new MyClassModelBinder()); 

然後使用輸出緩存這樣。

[OutputCache(Duration = 300, VaryByCustom = "myClass")] 
public ActionResult MyAction(MyClass myClass) 
{ 
    ....... 

public override string GetVaryByCustomString(HttpContext context, string custom) 
{ 
    ... check we're working with 'MyClass' 

    var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context)); 
    var myClass = (MyClass)routeData.Values["myClass"]; <-- This is always null 

myClass不在路由表事件中,但模型聯編程序被觸發。

一如既往的任何幫助將是最受歡迎的。

乾杯

回答

5

模型綁定模型不添加到RouteData,所以你不能指望從中獲取它。

一種可能性是將HttpContext內部模型存儲您的自定義模型粘合劑內:

public class MyClassModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var model = new MyClass(); 
     // ... build the class 

     // Store the model inside the HttpContext so that it is accessible later 
     controllerContext.HttpContext.Items["model"] = model; 
     return model; 
    } 
} 

,然後檢索它使用相同的密鑰(model在我的例子)的GetVaryByCustomString方法內:

public override string GetVaryByCustomString(HttpContext context, string custom) 
{ 
    var myClass = (MyClass)context.Items["model"]; 

    ... 
} 
+0

感覺有點哈克,但它的作品。乾杯。 – Magpie

+0

@Magpie,歡呼聲。 –