Output Caching in asp.net
Recently one of my friend ask about output cache so I decided to put a post about how output cache works and what is the advantages and disadvantage of using output cache. Output cache is a technique to cache generated response from the asp.net pages or controls. Output Caching increases the performance drastically by reducing server round trips. We can use @OutputCache directive to controls output caching for a page or controls.
The @OutputCache includes following attributes.
- Duration: This attribute will explain how long output cache will be there for a page or control. It can be set in seconds. If you set 60 then it will not going to generate response from server until 60 second It will generate response from the cache it self. Here is example of duration where it will set 60 second for page.
<%@ OutputCache Duration="60" %>
- VaryByParam: This attribute will determine cache entries based on get or post parameters. It will vary cache based on get or post parameters suppose you set product Id query string as VaryByParam it will create a different cache based on product Id. Following is a example how you can set the VaryByParam based on Product Id.
<%@ OutputCache Duration="Seconds" VaryByParam="ProductId"%>
- Location: This attribute will specify where the Item will be cached. Here are options available for that.
- Any: The output cache can be located at any browser from where request is generated or Server where request is processed or Proxy server participating in request.
- Client: The output cache will be located on browser client from where request is generated.
- Downstream: The output cache can be stored in any HTTP 1.1 cache-capable devices other than the origin server. This includes proxy servers and the client that made the request.
- Server: The output cache will stored in the server where generated request will be processed.
- ServerAndClient: The output cache will generated either on Browser where request generated or on server where generated request will be processed. Proxy servers are not allowed for this.
- None: None specifies that output cache will be disabled for this controls or Page.
<%@ outputcache duration="10" Location="Server" %>
- VaryByCustom: This attribute is for different browsers where request is generated this means it will generate new instance of cache based on different browser versions.
<%@ OutputCache Duration="Seconds" VaryByCustom="Browser" %>
<%@ OutputCache VaryByHeader="Accept-Language" %>Note: If you specify the output cache it will not fire server side events like click or selected index changed etc. So make sure the controls that you used in output cache will not have this kind of controls Or you have to handle this in other scenarios.
Hope this will help you.. Happy programming!!