user1615362
user1615362

Reputation: 3817

How to use OutputCache for a specific argument only?

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
    }
);

Upvotes: 0

Views: 415

Answers (1)

Brad Christie
Brad Christie

Reputation: 101614

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();
    }
}

Upvotes: 1

Related Questions