1

モデルバインドするクラスがあり、それで出力キャッシュを使用したいと思います。バインドされたオブジェクトにアクセスする方法が見つかりませんGetVaryByCustomString

例えば:

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はルートテーブルイベントに含まれていません。

いつものようにどんな助けでも大歓迎です。

乾杯

4

1 に答える 1

5

モデル バインダーはモデルを に追加しないRouteDataため、そこから取得することは期待できません。

HttpContext1 つの可能性は、カスタム モデル バインダー内にモデルを格納することです。

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;
    }
}

GetVaryByCustomString次に、同じキーを使用してメソッド内で取得します(model私の例では):

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

    ...
}
于 2012-06-25T20:26:08.853 に答える