0

I have this example of OutputCache. My problem is that I want the page to be cached only if the [id] equals to NULL. In all other cases I don't want to have cache at all.

MyController:

[OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
public ActionResult Details(int id)
{}

RouteConfig:

routes.MapRoute(
    name: "edit",
    url: "edit/{id}",
    defaults: new {
        controller = "asd",
        action = "Details",
        id = UrlParameter.Optional
    }
);
animuson
  • 53,861
  • 28
  • 137
  • 147
user1615362
  • 3,657
  • 9
  • 29
  • 46

1 Answers1

1

You can specify (and implement) the VaryByCustom parameter of OutputCacheAttribute:

MyController.cs

[OutputCache(Duration = int.MaxValue, VaryByCustom = "idIsNull")]
public ActionResult Details(int id)
{
}

Global.asax.cs

public override string GetVaryByCustomString(HttpContext context, string arg)
{
    if (arg.ToLower() == "idisnull")
    {
        return string.IsNullOrWhiteSpace(Request.QueryString["id"])
            ? string.Empty
            // unique key means it won't have a consistent value to use
            // as a cache lookup
            : ((new DateTime(1970, 1, 1) - DateTime.Now).TotalMilliseconds).ToString();
    }
}
Brad Christie
  • 100,477
  • 16
  • 156
  • 200