我有一个类我模型绑定,我想使用它的输出缓存。我无法找到一种方法来访问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不在路由表事件中。
随时欢迎任何帮助。
干杯
答案 0 :(得分: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;
}
}
然后使用相同的密钥(在我的示例中为GetVaryByCustomString
)在model
方法中检索它:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
var myClass = (MyClass)context.Items["model"];
...
}