I have a class I model bind and I want to use output caching with it. I can’t find a way to access the bound object in GetVaryByCustomString
For example:
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;
}
}
I set the binder in Global.cs
ModelBinders.Binders.Add(typeof(MyClass), new MyClassModelBinder());
And then use output caching like this.
[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 isn’t in the route table event though the model binder fired.
Any help as always will be most welcome.
Cheers
The model binder doesn’t add the model to the
RouteData, so you cannot expect to fetch it from there.One possibility is to store the model inside the
HttpContextinside your custom model binder:and then retrieve it inside the
GetVaryByCustomStringmethod using the same key (modelin my example):