我有一个模型绑定(bind)类,我想对其使用输出缓存。我找不到在 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 中设置了 Binder
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
虽然模型绑定(bind)程序已触发,但 myClass 不在路由表事件中。
一如既往地欢迎任何帮助。
干杯
最佳答案
模型绑定(bind)器不会将模型添加到 RouteData
,因此您不能指望从那里获取它。
一种可能性是将模型存储在自定义模型 Binder 中的 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"];
...
}
关于c# - VaryByCustom 和模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11196701/