How to cache an asp.net page depending on the user's browser language
This is my second post regarding caching in asp.net applications. You can find my other post in caching here.
A friend of mine asked me if he can control caching of an asp.net page depending on the user's language browser.
Let's see how we can accomplish that with a step by step example.
You can use any of the versions of Visual studio (VS 2005,VS2008,VS2010 express editions work fine).
I will use VS 2010 Ultimate edition and VB.net as the .Net language of choice.
We will identify the language of the user's browser from the HTTP headers.
More specifically we will look at the Accept-Language header item.
1) Create an Asp.net web site and name it as you want.Add a label web server control to your default.aspx page.
2) In the default.aspx just below the Page directive ( top of the page ) you add the
following bit of code:
<%@ OutputCache Duration="50" VaryByHeader="Accept-Language"
VaryByParam="none"
%>
We want to use VaryByHeader and assign it to the header item Accept-Language that we want to vary caching by.
So now this page is going to be cached based on the language of the user's browser.
3) Now switch back to the code behind and in the Page_Load event handling routine type the following
If Not (Request.Headers("Accept-Language")) Is Nothing Then
mylabel.Text = "language of the user is " + Request.Headers("Accept-Language").ToString
End If
4) Run your application and see the result-your browser's language. In most cases it will be something like "en-us", or anything else that the HTML page will output. So if now we have 20 people
hitting our page - within the 50 seconds cache period - and all of them have "en-us" as their browser's language they are going to get the cached version of the page. The page will not be re-rendered through the whole
page events-lifecycle.
5) If we have people hitting our page with a browser with a different language (.eg fr,es ) the Asp.Net would cache a second version of the page in french. So now we would have 2 cached versions of the page, one in english and one in french.So the first french person (browser language) to hit the page, he would see the page rendered to him ( the whole page lifecycle will run ) and at the same time it will be cached so subsequent requests from french people-users-browsers will be served from the cache.
If you need the code, just email me.
Hope it helps !!!