我有一个模型绑定的类,我想对其使用输出缓存。我找不到在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不在路由表事件中。

一如既往的任何帮助都将受到欢迎。

干杯

最佳答案

模型绑定程序不会将模型添加到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;
    }
}


然后使用相同的键(在我的示例中为GetVaryByCustomString)在model方法内检索它:

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

    ...
}

关于c# - VaryByCustom和模型绑定(bind),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11196701/

10-17 00:55