How can I use outputcache in this situation?

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

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

+3
source share
2 answers

Part of the output caching infrastructure is the VaryBy mechanism, which allows you to specify ASP.NET so that the parallel caches of a single page change over some part of the data, for example, in the query string. In this case, the VaryByCustom mechanism may be the easiest to implement. Here is a short article with a good example.

First, the cache attribute:

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

Cache Profile:

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

And finally, the user 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 returned Session["lang"], ASP.NET will store a cached copy of the page that runs under this parameter.

+1
source

Save this value in cookies, session not available in GetVaryByCustomString

-1
source

Source: https://habr.com/ru/post/1774435/


All Articles