where Duration and VaryByP"/> where Duration and VaryByP">
search
HomeBackend DevelopmentC#.Net TutorialA brief analysis of asp.net page caching technology

I have long wanted to write more about technology
Firstly, it is for myself to be more knowledgeableQuery, of course, everyone will learn more about it. Ha
No gossip
I just have some time today, so I will piece it together


PageCache
Use the OutputCache directive.
Location="Any"
VaryByCustom="browser"
VaryByParam="RequestID" %>
The Duration and VaryByParam attributes are required

Location controls the location of the page cache

#. ##LocationMeaning##AnyClientDownstreamServerNone


Duration allows us to control how long the page lives in the cache (in seconds)

VaryByParam allows us to cache different versions of the page. In the above example, VaryByParam is set to RequestID, so ASP.NET uses different values ​​​​of the RequestID parameter. These values ​​​​are either passed in the query string of HTTP GET, or It is passed in the parameters of HTTP POST. You can let the application distinguish between different users by checking the value of the RequestID parameter; by placing VaryByParam="RequestID" in the OutputCache directive of the page, you can let ASP.NET cache different versions of the page for each user.
If you don't want to cache the independent version of the page based on the value of the parameter, then just set VaryByParam to none.
You can also ask ASP.NET to cache a version of the page for each possible parameter array combination. To do this, set VaryByParam to *.

The VaryByHeader and VaryByCustom attributes are similar to VaryByParam in that they allow specifying when a new cached version of a page should be created.
VaryByHeader allows us to cache non-directed versions of a page based on a semicolon-separated list of HTTP headers.
VaryByCustom, when set to browser, allows us to cache different versions based on the browser's name and major version information. We can also set it to the name of a custom method to implement our own logic and control the cached version.

Fragment caching
You can use usercontrol to segment the page and write cached statements in the ascx file instead of writing cached statements in the aspx file , so that ASP.NET can only cache the output of the ascx fragment. Generally, if the header or footer is basically the same, there is no need to reload. However, if there is dynamically changing data, it cannot be cached, because once it is cached, the program will not create an instance of it to update the data display. It can only wait until the lifetime expires, so for This situation is not suitable for page fragment caching.
Note:
1. Note that fragment caching does not support the Location feature; the only legal place to cache page fragments is the web server. This is because fragment caching is a new feature in ASP.NET, so browsers and proxy servers do not support it.
2. Fragment cache has another feature that is not found in page cache - VaryByControl. The VaryByControl attribute allows you to specify a semicolon-delimited list of strings that represent the names of controls used within a user control; ASP.NET will generate a cached version of the user widget for each different combination of values.

Data Cache
Low-level API is the Cache class, which is located in the System.web.Caching namespace in ASP.NET, You can use it to cache resource-intensive data. The use of the Cache class is as simple as Session and Applicationobject. There is only one Cache object per application - this means that the data stored in the cache using the Cache object is application-level data. To make things even simpler, the Page class's Cache property makes the application's Cache object instance available in the code. Data cached through the Cache object is stored in the application's memory. This means that the lifetime of this data will not exceed the restart of the application (in fact, this is the same as the data stored in the Application and Session objects, unless StateService or SQL State session mode is used to store Session data).
The specific usage and syntax are the same as Session and Application. When converting back, you need to pay attention to the mandatory
type conversion of the corresponding type.
This is not the only way to add cache items in the ASP.NET cache. The Cache object has two methods, the Insert() method and the Add() method, which are more flexible. Their usage is similar, but slightly different:
The Insert() method is used to overwrite existing cache entries in the ASP.NET cache.
The Add() method is only used to add new cache items to the ASP.NET cache (if you use it to overwrite existing cache items, it will fail).
Each method has 7 parameters, and the parameters of the two methods are the same.
When caching an item, you can specify its relevance and tell ASP.NET that the cached item will remain in the cache until a certain
event occurs.




means the page. The output can be cached in the client browser, cached in any "downstream" client (such as a proxy server), or cached in the web server itself


Specifies that the output cache can only be stored in the local cache of the requesting client (i.e. the browser)


Specifies that the output cache can be stored in any device that supports HTTP1.1 caching (such as a proxy server)


Specifies the output cache Will be stored on the web server


Indicates that output caching is disabled for this page

##CacheDependency Allows specifying a file or cache key. If the file changes, the object is deleted. If the cache key changes, the object is also deleted. DateTimeThis is a DataTime value, indicating the TimeSpanThis is a time interval that indicates how long cached data can remain in the cache after the last access (elastic expiration time)
Relevance value
Meaning



cached data expiration time (absolute expiration time)


Use CacheItemPriority to specify the

priority of cached data so that low-priority data is deleted when the cache is filled.

Priority valueMeaningHighCache items set to this priority are the least likely to be deleted when out of memoryAboveNormal Cache items set to this priority will be retained more favorably than cache items with a priority of Normal or below NormalSet this priority Cache items with priority levels of BelowNormal and Low have priority to be retained.BelowNormalThis is the penultimate level of priority level; cache items set to this priority will only be retained in preference to cache items set to Low.LowSet to Cache entries of this priority are the DefaultThe default value for the priority of cache entries that are most likely to be deleted when out of memory Is Normal##NotRemovableDateTime dt = new DateTime(DateTime.Now.Year,12,31);















When the cache item is set to this priority, it is telling ASP.NET not to cache items even if there is insufficient memory. Delete it from cache

Cache.Add("MembersDataSet" ,dsMembers,null,

dt,TimeSpan.Zero,
CacheItemPriority.Normal,null);
The first parameter is the key that refers to the cache object, and the second parameter is the object to be cached. The third parameter is null (indicating no correlation).
The fourth and fifth parameters are absolute expiration time and flexible expiration time. Here, we specify that the cache should expire on the last day of the current year (dt). We want to specify a non-flexible expiration time, so use TimeSpan.Zero for the fifth parameter. The sixth parameter uses a value from the System.Web.Caching.CacheItemPriority enumeration to set the priority to Normal.

Specify a flexible expiration time of 5 minutes, no absolute expiration time is specified
Cache.Add("MembersDataSet",dsMembers,null,
DateTime.MaxValue,TimeSpan.FromMinutes(5),
CacheItemPriority.Normal,null);

Add a correlation. In this example, the expiration time also depends on the modification of a file, the test.xml file:
CacheDependency dep = new CacheDependency(@"C:/test.xml");
Cache.Add("MembersDataSet ",dsMembers,dep,
DateTime.MaxValue,TimeSpan.FromMinutes(5),
CacheItemPriority.Normal,null);

The expiration time depends on the modification of another item in the cache:
String[] dependencyKeys = new String[1];
dependencyKeys[0] = "MembersChanged";
CacheDependency dependency = new CacheDependency(null, dependencyKeys);
Cache.Add("MembersDataSet",dsMembers ,dependency,
DateTime.MaxValue,TimeSpan.Zero,
CacheItemPriority.Normal,null);

The last parameter is of type CacheItemRemovedCallback, allowing us to request notification when a cache item is deleted from the cache , you can write a custom method (like the ItemRemovedCallback() method here), and then specify the method in the 7th parameter:
public void ItemRemovedCallback(String key, Object value, CacheItemRemovedReason reason)
{
}

Cache.Add("MembersDataSet",dsMembers,dependency,
DateTime.MaxValue,TimeSpan.FromMinutes(5),
CacheItemPriority.Normal,
new CacheItemRemovedCallback(this. ItemRemovedCallback));
The first parameter is the key used when storing the cache item in the cache, the second is the stored object itself, and the third is the reason for the cache item removal.


A brief analysis of asp.net page caching technology

The above is the detailed content of A brief analysis of asp.net page caching technology. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# .NET Interview Questions & Answers: Level Up Your ExpertiseC# .NET Interview Questions & Answers: Level Up Your ExpertiseApr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool