Caching Output by Culture


ASP.NET's caching mechanism makes a considerable difference to an application's performance. When a page is requested for the first time, a copy of the page is placed in a cache. Subsequent requests for the same page get the page from the cache without having to regenerate the page again. Caching is important from an internationalization viewpoint because your caching mechanism needs to respect the culture of the cached page. However, by default, the caching mechanism does not. Consider what happens in an application that caches pages without respect for the page's culture. Let's say the page's script includes the following line to cache the page for 5 minutes:

 <% @Outputcache Duration=300 VaryByParam=none%> 


When the first user requests this page, it will be added to the cache. Let's say that the first user has a language preference of French (France). From here on, all users requesting this page will receive the cached pagei.e., the French (France) pageregardless of their own language preference. This is not helpful. We need to cache the page by culture. The solution is to cache by culture using a custom string:

 <% @Outputcache Duration=20 VaryByParam=none VaryByCustom="CurrentUICulture"%> 


The VaryByCustom attribute enables us to specify a custom string that we can use to identify the criteria by which the page is cached. This string is passed to the HttpApplication.GetVaryByCustom method. We override this method (in global.asax) and check the custom string:

 public override string GetVaryByCustomString(     HttpContext context, string custom) {     if (String.Compare(custom, "CurrentUICulture", true,         CultureInfo.InvariantCulture) == 0)         return CultureInfo.CurrentUICulture.Name;     else         return base.GetVaryByCustomString (context, custom); } 


The GetVaryByCustomString method returns a string that identifies the version of the page. In the previous example, the first user to access the page would have a CurrentUICulture of "fr-FR". Their copy of the page would be cached as the "frFR" page. If the second user to access the page had a language preference of English (United States), the cache would be searched for the requested page with a custom CurrentUICulture of "en-US". Because no such page would be in the cache at this point, the page would be generated and added to the cache. Subsequent requests for "fr-FR" or "en-US" pages within 5 minutes would receive the appropriate cached page.




.NET Internationalization(c) The Developer's Guide to Building Global Windows and Web Applications
.NET Internationalization: The Developers Guide to Building Global Windows and Web Applications
ISBN: 0321341384
EAN: 2147483647
Year: 2006
Pages: 213

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net