Search code examples
c#asp.netasp.net-mvcoutputcache

How can I use outputcache at this situation?


In my application, I will remember user's language choice in session. The problem is if I use output cache, then the change language function will not work, because it caches the result when I retrieve from database according to the Session["lang"] value.

So if I have another method to use cache function ? Or how can I decrease the response time ?


Solution

  • Part of the Output Caching infrastructure is the VaryBy mechanism, which is a way to instruct ASP.NET to keep parallel caches of the same page varied by some piece of data, like a querystring. In this case, the VaryByCustom mechanism may be the simplest to implement. Here's a short article with a good example.

    First, the caching attribute:

    [OutputCache(CacheProfile = "CachedPage")]
    public ActionResult Index()
    {
       return View();
    }
    

    The cache profile:

    <caching>
        <outputcachesettings>             
            <outputcacheprofiles> 
                <add varybycustom="Language"
                     varybyparam="*"
                     duration="86400"
                     name="CachedPage" />
            </outputcacheprofiles> 
        </outputcachesettings> 
    </caching>
    

    And finally, the custom logic in global.asax.cs:

    public override string GetVaryByCustomString(
        HttpContext context,
        string arg)
    {
        if (arg == "Language")
        {
             return Session["lang"].ToString();
        }
        else
        {
            return base.GetVaryByCustomString(context, arg);
        }
    }
    

    Now for each possible unique value that Session["lang"] returns, ASP.NET will keep a cached copy of the page which executed under that parameter.