asp.net cache__.net

Source: Internet
Author: User
Tags date1

Original address: Http://www.codeproject.com/KB/aspnet/AspDotNetCache.aspx

Caching is a technology that stores very time-consuming data in memory and is an important feature of ASP.net. For example, you can cache data that is time-consuming and complex, and subsequent requests need not be fetched from the database and taken directly from the cache. By caching, you can greatly improve the performance of the program.

There are two main types of caching:

1. Output Caching

2. Data caching


1. Output Caching (export cache)

Using output caching, you can cache the final generated HTML of the page. The cached page works when the same page is requested again. Asp. NET no longer executes the page's lifecycle and related code. Syntax for output caching:

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ OutputCache Duration = "a" VaryByParam = "None"%>

The Duration property settings page will cache 60 seconds for the first request in all user requests, ASP. NET executes the page code, renders the resulting HTML results to the user and saves them in the cache. If the server again receives a request for the same page within 60 seconds, ASP. NET automatic send cache Backup page to the user. If the server receives a request after the cache expires, ASP. NE executes the page code and creates a new HTML cache for the next 60 seconds.

<%@ Page language= "C #" masterpagefile= "~/masterpage.master" autoeventwireup= "true"
        codefile= " OutputCachingTest.aspx.cs "inherits=" Outputcachingtest "title=" Untitled Page "%> <%@ OutputCache duration=
 "Varybyparam=" "None"%>
 <asp:content id= "Content1" contentplaceholderid= "ContentPlaceHolder1" runat= " Server > 
   <div class= "title" >output cache</div>
   Date: <asp:label id= "Lbldate" Server "text=" "/> Time
   : <asp:label id=" Lbltime "runat=" Server "text=" "/>       
 </asp:Content>
protected void Page_Load (object sender, EventArgs e)
{
   lbldate.text = DateTime.Now.ToShortDateString ();
   Lbltime.text = DateTime.Now.ToLongTimeString (); 

In this case, the page will be cached for 20 seconds.


Cache by query string (cached by query strings)

In practical applications, dynamic pages change the content of the page according to the parameters. If your page is receiving information through a query string, you can also easily cache different copies of the page based on the query string. Varbyparam= "None" tells ASP.net to store only one copy of the page. varbyparam= "*" tells ASP.net to store different page copies based on different query strings.

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ OutputCache Duration = "a" VaryByParam = "*"%>
2
3 < div align = "right" >
4 < a href = "outputcachingtest2.aspx" > No Query String </a > |
5 < a href = "outputcachingtest2.aspx?id=1" > ID 1 </a > |
6 < a href = "outputcachingtest2.aspx?id=2" > ID 2 </a > |
7 < a href = "outputcachingtest2.aspx?id=3" > ID 3 </a > |
8 < a href = "outputcachingtest2.aspx?id=3&langid=1" > ID 3 </a >
9 </div >

In the same page, by passing a different query string ID value, the ASP. NET stores a copy of each ID value, which is a good use in this case, but there are some problems. If the page receives a wide range of query strings, then ASP. NET caches a copy of each query string parameter and potentially reduces reusability. In this case, you can specify several more important query parameters in the Varbyparam attribute.

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @OutputCacheDuration = "VaryByParam" = "Id;langid"%>

As set above, ASP. NET caches different versions based on different "id" or "langid" query string values


Custom Caching (Customize Cache)

You can also create a custom page caching process. Asp. NET provides a convenient way to create a custom cache by specifying a custom cache type for the Varbycustom property.

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ OutputCache Duration = "no" VaryByParam = "None" VaryByCustom = "Browser"%>

You need to create a method that generates a custom cache string. The syntax is as follows:

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 public override string GetVaryByCustomString (HttpContext context, string Custom)
2 {
3 if (custom = "Browser")
4 {
5 return context. Request.Browser.Browser +
6 context. Request.Browser.MajorVersion;
7}
8 Else
9 {
Ten return base. GetVaryByCustomString (context, custom);
11}
12}

The method must be written in the Global.asax file, returning a string value. Asp. NET uses this value to implement caching. If different request methods return the same string value, asp.net reuses the cached page unless a new cached version is produced. In the example above, getvarybycustomstring () creates a cached string based on the browser name. Asp. NET creates different versions of the cache based on different browser requests.


Control Cache (controls caching)

The caching technique above allows you to easily cache the entire page. But if you want to cache the specified control content, you can cache a control by VaryByControl the property

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ OutputCache Duration = "a" VaryByControl = "Mycontrol_1"%>

Add the above code on the. aspx page, asp.net will cache the Mycontrol_1 control for 20 seconds, so asp.net creates a "mycontrol_1" cached version, and if the cache does not expire, asp.net reuse the cached version unless the control code is executed again. ASP.net is also handy if you want to create a control cache that relies on some of the properties of the control, simply by adding the OutputCache directive on the *.ascx control page.

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ Control Language = "C #" AutoEventWireup = "true"
2 CodeFile = "MyControl.ascx.cs" Inherits = "Controls_mycontrol"%>
3 <% @ OutputCache Duration = "VaryByControl" = "EmployeeID"%>
4. ...
5. ...

Varybycontrol= "EmployeeID" tells ASP.net to create different control cache versions based on control properties EmployeeID different values.

Add the property "Emplyeeid" to the. ascx.cs file to asp.net create the cache

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 private int _employeeid;
2 public int EmployeeID
3 {
4 get {return _employeeid;}
5 set {_employeeid = value;}
6}
7
8 protected void Page_Load (object sender, EventArgs e)
9 {
Lbldate.text = DateTime.Now.ToShortDateString ();
One lbltime.text = DateTime.Now.ToLongTimeString ();
12
Lblemployeeid.text = Employeeid.tostring ();
14
15}

Add a control to the page and set the "EmployeeID"

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ Register SRC = "Controls/mycontrol.ascx" TagName = "mycontrol" TagPrefix = "uc1"%>
2 < Asp:content ID = "Content1" ContentPlaceHolderID = "ContentPlaceHolder1" runat = "Server" >
3 < div align = "center" >
4 < Uc1:mycontrol ID = "MyControl1" runat = "server" EmployeeID = "1" ></Uc1:mycontrol >
5 </div >
6 </asp:content >

Cache Profile (cached configuration file)

ASP.net is also quite handy for defining cache settings in Web.config files. If you embed the cache settings in the page and want to change from 20 seconds to 30 seconds, then you must alter the duration value in all pages. The best way to do this is to set up caching in Web.config, and you can easily manage your cache settings.

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 < system.web >
2 < caching >
3 < outputCacheSettings >
4 < outputCacheProfiles >
5 < add name = "Productitemcacheprofile" duration = "/>"
6 </outputcacheprofiles >
7 </outputcachesettings >
8 </Caching >
9 </system.web >

Now all you need to do is add cacheprofile= "profilename" to the page properties. <!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 <% @ OutputCache cacheprofile = "Productitemcacheprofile" VaryByParam = "None"%>

Data caching (date cache)

ASP.net also provides a flexible data cache. You can add some resource-consuming items to the object cache collection. Cache is a collection of key-value pairs, and adding items to the cache collection requires only a new key name to be specified.

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 cache["Name" = data;

The technology does not support caching object control. Cache.Insert () provides the 5 version of the method overload, by using the Insert method, you can set the cache expiration policy, priority, dependencies, and so on.

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 date1 = DateTime.Now;
2 Cache.Insert ("Date1", date1, NULL, DateTime.Now.AddSeconds (), TimeSpan.Zero);

asp.net allows you to set an absolute or relative expiration policy, but you can use only one at a time.


cache dependency (cached dependencies)

You can also set a cache dependency in ASP.net, which allows one cache entry to depend on another, but the cached item is automatically removed when the resource changes. The CacheDependency class is used to create dependencies. This class has multiple constructors. You can create dependencies on files or folders. If a file or folder changes, the cache expires. You can also create dependencies that depend on other cache entries.

<!--

Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> 1 date2 = DateTime.Now;
2
3 string [] Cachekeys = {"Date1"};
4 CacheDependency CACHEDEPN = new CacheDependency (null, cachekeys);
5 Cache.Insert (

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.