Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache based on Url Parameter in Asp.net MVC

i have defined a route culture/Controller/action/id... my controller contains following action..

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

is it possible to Cache contents based on Culture?

like image 810
Usman Masood Avatar asked Mar 18 '26 11:03

Usman Masood


1 Answers

The localization complete guide presents an example of how to achieve this using the VaryByCustom parameter. In global.asax you would override the GetVaryByCustomString method:

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 could 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);
}
like image 156
Darin Dimitrov Avatar answered Mar 21 '26 01:03

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!