2012-06-25 2 views
1

클래스 I 모델 바인딩이 있고 출력 캐싱을 사용하고 싶습니다. 나는 예를 들어 GetVaryByCustomStringVaryByCustom 및 모델 바인딩

에 바인딩 된 개체에 액세스 할 수있는 방법을 찾을 수 없습니다 : 나는

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

Global.cs

에 바인더를 설정 한 다음과 같은 출력 캐싱을 사용
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; 
    } 
} 

.

[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에 모델을 추가하지 않습니다, 그래서 당신은 거기에서 그것을 가져 기대할 수 없다.

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"]; 

    ... 
} 

하나의 가능성은 사용자 정의 모델 바인더 내부의 HttpContext 내부 모델을 저장하는 것입니다

+0

조금 해킹 된 느낌이지만 작동합니다. 건배. – Magpie

+0

@Magpie, 건배. –