Cache based on URL parameter in Asp.net MVC

I defined the route culture / Controller / action / id ... my controller contains the following action.

 [OutputCache(Duration=60*10)]
        public ActionResult Index()
        {*/do magic here/*}

is culture based cache content possible?

+3
source share
1 answer

A complete localization guide provides an example of how to achieve this using a parameter VaryByCustom. In global.asax, you override the method GetVaryByCustomString:

public override string GetVaryByCustomString(HttpContext context, string value)
{
    if (value == "lang")
    {
        return Thread.CurrentThread.CurrentUICulture.Name;
    }
    return base.GetVaryByCustomString(context, value);
}

and then:

[OutputCache(Duration = 60 * 10, VaryByParam = "none", VaryByCustom = "lang")]
public ActionResult Index()
{
    /* do magic here */
    ...
}

Or if you want to rely solely on the culture route data parameter, you can do this:

public override string GetVaryByCustomString(HttpContext context, string value)
{
    if (value == "lang")
    {
        var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
        var culture = (string)routeData.Values["culture"];
        if (!string.IsNullOrEmpty(culture))
        {
            return culture;
        }
    }
    return base.GetVaryByCustomString(context, value);
}
+4
source

All Articles