3

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 ?

MemoryLeak
  • 7,322
  • 23
  • 90
  • 133

2 Answers2

1

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.

Rex M
  • 142,167
  • 33
  • 283
  • 313
  • I read something like this before, but it seems does not work, it always caches the result. – MemoryLeak Nov 12 '10 at 03:32
  • 1
    @MemoryLeak when implemented correctly I assure you it works quite well. – Rex M Nov 12 '10 at 03:46
  • 3
    I found the Context.Session is null, it is not supposed to be null ! What's up ? – MemoryLeak Nov 12 '10 at 03:47
  • 3
    @MemoryLeak - You cant access Session in `GetVaryByCustomString`, it's not there yet - it's created in `Application_AcquireRequestState`. Try using something else for the vary-ator (is that a word?). URL/Cookies maybe? – RPM1984 Nov 12 '10 at 03:55
  • 1
    oh, is there any other choices ? As I have implemented all the logic, I don't want to change it, yup, it's a string. – MemoryLeak Nov 12 '10 at 04:01
  • Downvoted because Session is not available in GetVaryByCustomString, as AcquireRequestState hasn't yet fired. – defines Sep 08 '15 at 19:57
-1

Save this value in cookies, session are not available in GetVaryByCustomString