TOC

This article is currently in the process of being translated into Spanish (~16% done).

Caching:

OutputCache - more examples

En el capítulo anterior revisamos cómo usar la directiva OutputCache para crear la caché de nuestra página fácilmente. En este capítulo veremos otras formas de usar OutputCache. Usamos varybyparam en el anterior ejemplo, pero también puedes variar tu caché con otros factores. Aquí hay una lista y algunos ejemplos.

OutputCache - varybyparam

Por favor, vea el capítulo anterior para más información sobre el parámetro varybyparam

OutputCache - varybycontrol

The varybycontrol does exactly what it says - it varies the cache depending on the value of the specified control. For instance, you can have a dropdownlist with a set of selections, and base the content of the page based on the selected item. In that case, it will make sense to vary by the value of this control, since the content of the page changes according to it. Here is an example of using the varybycontrol parameter:

<%@ OutputCache duration="10" varybyparam="none" varybycontrol="NameOfControl" %>

OutputCache - varybycustom

This is probably the least easy way of using the OutputCache system, but on the other hand, probably the most flexible. It allows you to handle the variations your self, by setting a custom string, which ASP.NET will vary the output by. To test this, you need to add a global.asax file to your project, if you don't already have one. Right click on your project in the Solution Explorer, and select Add new item. Now select the "Global Application Class" and click Ok. In the Global.asax file, you need to override the GetVaryByCustomString like this:

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if(custom == "Browser")
    {
        return context.Request.Browser.Browser;
    }
    return String.Empty;
}

In this case, our caching will be varied based on which browser the user accesses the page with. The markup part should be written like this:

<%@ OutputCache duration="120" varybyparam="None" varybycustom="Browser" %>

Try accessing the page from different browsers. You will see that the output now depends on which browser you use. The Browser object comes with a bunch of useful information about the client browser - for instance you could vary by whether or not the browser supports CSS, JavaScript or something else.

OutputCache - varybyheader

This one allows you to vary the content based on one or more of the headers that browser send. Here is an example:

<%@ OutputCache duration="120" varybyparam="None" varybyheader="Accept-Language" %>

This will vary cache based on the Accept-Language header, which tells the server which languages the user accepts and prefers.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!