Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement caching in ASP.Net

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to implement caching in ASP.Net. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

1. Page caching

To implement page output caching, simply add an OutputCache instruction to the page.

CacheProfile

The name used to define the cache settings associated with the page. Is an optional attribute and the default value is an empty character ("). It is important to note that the @ OutputCache directive contained in the user control does not support this property. When you specify this property on the page, the property value must match the name of one of the available items in the outputCacheProfiles element under the configuration section of the Web.config file. If this name does not match the profile entry, an exception is thrown.

NoStore

This property defines a Boolean value that determines whether to block secondary storage of sensitive information. It is important to note that the @ OutputCache directive contained in the user control does not support this property. Setting this property to true is equivalent to executing the code "Response.Cache.SetNoStore ();" during the request.

Duration

Used to set the time for the page or user control cache. The unit is seconds. By setting this property, you can establish an expiration policy for the HTTP response from the object and automatically cache the page or user control output. It is important to note that the Duration attribute is required, otherwise it will cause a parser error.

Shared

This property defines a Boolean value that determines whether user control output can be shared by multiple pages. The default is false. Note that the @ OutputCache directive contained in the ASP.NET page does not support this attribute.

Location

Lets you specify the location of the output cache item. Its property values are OutputCacheLocation enumerated values, which are Any, Client, Downstream, None, Server, and ServerAndClient. The default value is Any, which means that the output cache can be used for all requests, including client browsers, proxy servers, or servers that process requests. It is important to note that the @ OutputCache directive contained in the user control does not support this property.

SqlDependency

This property identifies a set of string values for database / table name pairs on which the output cache of a page or control depends. It is important to note that the SqlCacheDependency class monitors tables in the database on which the output cache depends, so when updating items in the table, using table-based polling removes them from the cache. When notifications (in SQL Server 2005) are used with the CommandNotification value, the SqlDependency class is eventually used to register query notifications with the SQL Server 2005 server. In addition, the CommandNotification value of the SqlDependency property is valid only in ASP.NET pages. Control can only use table-based polling for the @ OutputCache instruction.

VaryByControl

This property uses a semicolon-separated list of strings to change the output cache of the user control. These strings represent the value of the ID property of the ASP.NET server control declared in the user control. Unless the VaryByParam attribute is already included, it is required in the @ OutputCache directive.

VaryByCustom

Any text used to customize output cache requirements. If the property is assigned a value of browser, the cache will vary depending on the browser name and major version information. If you enter a custom string, you must override the HttpApplication.GetVaryByCustomString method in the application's Global.asax file.

VaryByHeader

This attribute contains a semicolon-delimited list of HTTP headers to change the output cache. When this property is set to multiple headers, the output cache contains a different version of the request document for each specified header. The VaryByHeader property enables cached entries in all HTTP 1.1 caches, not just ASP.NET caches. This property is not supported by the @ OutputCache directive in the user control.

VaryByParam

This property defines a semicolon-delimited list of strings to change the output cache. By default, these strings correspond to query string values sent with the GET method property, or to parameters sent with the POST method. When this property is set to multiple parameters, the output cache contains a different version of the request document for each specified parameter. Possible values include "none", "*", and any valid query string or POST parameter name. It is worth noting that this property is required when outputting cached ASP.NET pages. It is also required for the user control unless the VaryByControl property is already included in the @ OutputCache directive of the user control. If not, a parser error occurs. If you do not need to change the cache contents with any specified parameters, you can set this value to "none". If you want the output cache to change based on all parameter values, set the property to "*".

Create page output cache file dependencies

Sample code: Response.AddFileDependency (MapPath ("test.xml"))

If you need to establish a dependent multi-file relationship, use the AddFileDependencies () method.

Set page cache expiration programmatically

Sample code: HttpResponse.RemoveOutputCacheItem (Page.ResolveUrl ("~ / test.aspx"))

This method accepts only one "virtual absolute" path, so you need to convert it with the Page.ResolveUrl () method.

Set multiple page cache expiration programmatically (create key dependencies (key dependency))

Sample code:

Cache page: PageLoad:

Cache.Insert ("key", DateTime.Now)

Response.AddCacheItemDependency ("key")

Use this method to add dependencies to multiple pages

Remove dependencies: PageLoad:

Cache.Remove ("key")

Manipulate the page output cache programmatically

Methods that manipulate HttpCachePolicy class objects exposed by the Response.Cache property.

Create a page output cache configuration

The copy code is as follows:

two。 Partial page cache

Replace after caching

Declaratively, use the Substitution control to set the MethodName property, which must be static, because the page instance has not been created when the current page output cache is in place. Note: post-cache substitution is used internally in AdRotator.

Replace after setting the cache programmatically, using the Response.WriteSubstitution () method, the benefits: 1, the method referenced by this method is not necessarily the method of the current class, but can be the strength or static method of another class. 2, you can use this method to implement post-cache substitution in custom controls.

Partial page cache: user control cache

Add instructions to the user control. This directive contains a Shared property that sets the output cache of the shared user control.

Set up the user control cache programmatically

When instructions are included in the user control, you can control how the modification space is cached through the properties of the instance of the ControlCachePolicy class exposed by the CachePolicy property of the user control.

Create file dependencies for user control cache

You can use the CacheControlPolicy.Dependency property to create a dependency between a cached user control and a file in the file system, sample code:

PageLoad:

CacheDependency depend=new CacheDependency (MapPath ("~ / test.xml"))

This.CachePolicy.Dependency=depend

Cache dynamically loaded user controls

You can load a user control using the Page.LoadControl () method, and when a user control with caching properties is loaded, Asp.net Framework automatically wraps the user control with an instance of the PartialCachingControl class. Sample code:

PageLoad:

PartialCachingControl cacheme= (PartialCachingControl) Page.LoadControl ("test.ascx")

Cacheme.CachePolicy.SetExpires (DateTime.Now.AddSeconds (10))

PlaceHolder1.Controls.Add (cacheme)

Lable1.Text=cacheme.CachePolicy.Duration.ToString ()

3. Use DataSource caching

SqlDataSource, ObjectDataSource, and XmlDataSource controls all include properties for caching DataSource hosts, with the advantage that data source controls can automatically reload data when the data is updated. And the same data can be shared among multiple pages, which can be identified by a combination of attributes: SelectCommand, SelectParameters, ConnectionString. If the attributes are the same, the same cached data is shared.

Set the cache expiration policy by setting properties

Includes absolute cache (EnableCaching= "True" CacheDuration= "xxx") and Sliding cache (EnableCaching= "True" CacheExpirationPolicy= "Sliding" CacheDuration= "xxx")

Using ObjectDataSource control caching

This is done by setting the EnableCaching, CacheExpirationPolicy, and CacheDuration properties of the control and the method name specified by SelectMethod.

Using XmlDataSource control caching

Set the DataFile property to create a file dependency.

Create a data source control key value dependency

Operation steps

1. Set the CacheKeyDependency property (key) of the data source control

2. Create an initialized (key) cache project in Global.asax. The code is as follows:

The copy code is as follows:

Void Application_Start (Object Sender,EventArgs e)

{

HttpContext context=HttpContext.Current

Context.Cache.Insert (

"key", DateTime.Now,null,DateTime.MaxValue,Cache.NoSlidingExpiration,CacheItemPriority.NotRemovable,null

);

}

3. Remove the cache item (key) on the page used to change the data

If you reinsert the cached item in the ItemInserted event of the DetailsView control, each DataSource that depends on this key will automatically reload the data as follows:

The copy code is as follows:

Protected void DetailsView_ItemInserted (object sender,DetailsViewInsertedEventArgs e)

{

Cache.Insert ("key", Datetime.Now)

}

Note: it is not necessary to use the current time for the above key values.

4.Cache object

You can add almost any object to the cache, for example, you can add custom controls, DataSet,DataTable,ArrayList, and List to the cache. Note: with any item returned from the cache, you should always check to see if the item is empty, and if an item has been deleted, it will return null when you try to read from the cache in the future.

View msdnCache members for more information

Add data cache to the Cache object sample code:

The copy code is as follows:

Void Page_Load ()

{

DataTable dt= (DataTable) Cache ["dtkey"]

If (dt==null)

{

Dt=getdtFromDB (); / / call the method here to return the data item DataTable from the database

Cache.Insert ("dtKey", dt,null,DateTime.Now.AddHours (1), Cache.NoSlidingExpiration); / / add items here using absolute expiration policy

}

GridView1.DataSource=dt

GridView1.DataBind ()

}

Private DataTable getdtFromDB ()

{

/ / slightly.

}

Add projects using dependencies

Asp.net Framework includes three cache dependencies

1. CacheDependency-- is used to create a file dependency or cache key-value dependency.

2. SqlCacheDependency-- is used to create a dependency on Microsoft SQL Server database tables or SQL Server 2005 database queries.

3. AggregateCacheDependency-- is used to create dependencies using multiple CacheDependency objects, for example, you can use this object to combine files and Sql dependencies.

The CacheDependency class is the base class, from which the other two classes inherit.

Specify cache project priority

You can specify any value of the CacheItemPriority enumeration type.

Configure cach

View the Msdn Caching element for more information

5. Using SQL cache dependencies

Asp.net Framework supports two types of SQL cache dependencies: pull and push. The first mode uses the ASP.NET implementation of table polling, and the second mode uses the query notification feature of SQL Server 2005. You can use pull SQL cache dependencies on any recent version of Ms SQL Server, including Ms SQL server 2005 Express, Ms SQL Server 2000, and Ms SQL Server 7. 0. The second type of push cache dependency can only be used with Ms SQL Server 2005 and Ms SQL server 2005 Express because they rely on SQL Server's Service Broker.

Use pull SQL cache dependency

Essentially, pull SQL cache relies on using database tigger. When the table is modified, tigger is triggered, a row of data in the data table named AspNet_SqlCacheTablesForChangeNotification is updated to record the changes, and Asp.net Framework uses a background thread to pull the modification information of the data table on a regular basis. If there are modifications, the cached items that depend on the data table are removed.

Configure pull SQL cache dependency:

1. SQL cache dependency must be enabled for one or more database tables.

You can use the SqlCacheDependencyAdmin class in the framework to configure the SQL database to support pull SQL cache dependencies. Because the methods of calling this class require the creation of tables, stored procedures, and trigger, for security reasons, the Asp.net process should not be given these permissions, but rather use this class through a command line tool.

Visit the Msdn ASP.NET SQL Server Registration tool (Aspnet_regsql.exe) for aspnet_regsql details

Brief steps: 1. Enable SQL cache dependency for a specific database.

Aspnet_regsql-c "Data Source=localhost;integrated Security=True;Initial Catalog=Pubs"-ed

2. Enable SQL cache dependency for specific tables.

Aspnet_regsql-c "Data Source=localhost;integrated Security=True;Initial Catalog=Pubs"-ed-t Titles

2. SQL cache dependencies must be configured in the Web configuration file.

The copy code is as follows:

/ / pull the database modification regularly through the setting of pollTime

A. Use pull SQL cache for page output cache dependency: instruction to specify sqlDependency attribute values: library name and table name (Mydatabase:Mytable)

B. Use pull SQL cache dependency on DataSource control: specify values for the DataSource control sqlDependency property: library name and table name (Mydatabase:Mytable)

C. Use pull SQL cache dependency on Cache objects:

The copy code is as follows:

Void Page_Load ()

{

DataTable dt= (DataTable) Cache ["dtkey"]

If (dt==null)

{

Dt=getdtFromDB (); / / call the method here to return the data item DataTable from the database

SqlCacheDependency sqlDepend=new SqlCacheDependecy ("Mydatabase", "Mytable")

Cache.Insert ("dtKey", dt,sqlDepend)

}

GridView1.DataSource=dt

GridView1.DataBind ()

}

Private DataTable getdtFromDB ()

{

/ / slightly.

}

Use push SQL cache dependency

Through Service Broker, you can automatically send a message to the application when the data in the database changes.

Benefit: Asp.net applications do not have to pull database modifications regularly.

Disadvantages: there are many restrictions on the type of query (for example, you must use a two-part indication: abo.mytabel, the query must contain a displayed column name indicating that you cannot use *, cannot reference views, temporary tables, etc., cannot include subqueries, external joins, child joins, large objects, DISTINCT, COMPUTE, COMPUTE BY, INSERT keywords, many aggregate functions, etc.)

1. Configure the database for pushing SQL cache dependencies

Enable Ms SQL Server 2005 Service Broker:

A, you can use: Select name, is_broker_enabled from sys_databases, query whether to activate a specific database.

B, through: Alter Database MyBase Set ENABLE_BROKER, enable.

C. Give the required permissions to the local AspNet account, such as Grant Subscribe Query Notifications To "yourserver\ Aspnet"

In other words, sql caches only support ms sql server 2005 or above for the time being before they rely on notifications. Otherwise, the cache is invalid.

two。 Configure the application for pushing SQL cache dependencies

The copy code is as follows:

Void Application_Start (object sender, EventArgs e)

{

String conString=WebConfigurationManager.ConnectionStrings ["MyContention1"] .ConnectionString

SqlDependency.Start (conString)

HttpContext context=HttpContext.Current

Context.Cache.Insert (

"key", DateTime.Now,null,DateTime.MaxValue,Cache.NoSlidingExpiration,CacheItemPriority.NotRemovable,null

);

}

A. Use push SQL cache dependency for page output cache:

When caching an entire Asp.net page, you can use push Sql cache dependencies. If the results of any Sql commands included on the page change, the page automatically expires from the cache.

The SqlCommand object contains a NotificationAutoEnlist property, which defaults to true. When NotificationAutoEnlist is enabled, a push cache dependency is automatically created between the page and the command. Note that the SelectCommand of the SqlDataSource must meet the query requirements.

B. Use push SQL cache dependency on DataSource controls:

You just need to set the SqlcacheDependency property. Set SqlCacheDependency= "CommandNotification"

C. Use push SQL cache dependency on Cache objects:

The copy code is as follows:

Void Page_Load ()

{

DataTable dt= (DataTable) Cache ["dtkey"]

If (dt==null)

{

String conString=WebConfigurationManager.ConnectionStrings ["MyContention1"] .ConnectionString

SqlDatadapter dad=new SqlDataAdapter ("Select aforme b From dbo.Mytable", conString); / / Note that the query meets the requirements

SqlCacheDependency sqlDepend=new SqlCacheDependecy (dad.SelectCommand)

Dt=new DataTable ()

Dad.Fill (dt)

Cache.Insert ("dtKey", dt,sqlDepend)

}

GridView1.DataSource=dt

GridView1.DataBind ()

}

Notice that an example of the SqlCacheDependency class is created. A SqlCommand object is passed to the constructor of the SqlCacheDependency class. If the result of the SqlCommand changes, the DataTable will automatically expire from the cache. The order of these commands is important. You must create a SqlCacheDependency object before executing this command. If the Fill () method is called before the SqlCacheDependency object is created, the dependency is ignored.

This is the end of the article on "how to implement caching in ASP.Net". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report