Original article address:Cache Technology in Web development: Implementing cache processing through etag (ASP. NET) Author:Selience
IIS has provided us with its built-in cache function. But it seems relatively rigid. For higher requirements, the cache function of IIS is obviously not flexible enough.
In MVC-style development, we can use filters to customize cache methods.
This article describes how to use the etag response header to implement caching without a perfect caching solution. This method can accurately determine whether the client browser cache needs to be updated, but does not prevent the server from generating the page again, its main purpose is to avoid unnecessary data transmission and reduce traffic to relieve bandwidth pressure.
What is etag and is-non-match
You can understand etag as an additional information in HTTP Communication. The server generates etag, when the client browser accesses this page again, this value is placed in is-non-match in request headers. Etag and is-non-match are used for caching. The following describes in detail how to use etag to implement cache processing in ASP. net mvc.
For more information about etag, see W3C instructions:Http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Basic Principles
Before the server passes the data to the client's browser, it will hash the page data, convert the hash value to base64 encoded ASCII characters, and store them in the etag information of the response header. The client browser caches the etag value locally after receiving information from the server, the next time you access this page, the etag value will be placed in the is-non-match in the Request Header. The server will still generate the page, but you need to compare it with the etag value, if they are the same, it means that the cached page in the client browser is consistent with the content to be transmitted. In this case, the duplicate page is not transmitted, but the status is set to 304, this reduces unnecessary bandwidth usage.
How to Implement
What we need to do is to let the Server Accept the response and generate data, but check the content to be written before writing it to the stream, check whether the hash calculated value is the same as the value in is-non-match. If the value is the same, set the HTTP status to 304. Otherwise, update etag and write data to the stream. To achieve this goal, I defined a packaging stream, replacing httpresponsebase. filter with a packaging stream, so that we can obtain data before the data is sent to the client.
(Note: The actionfilter of Asp.net MVC is not the same as the filter in Java. At first, I thought that the content written in response already exists when onresultexecuted is executed, later, I found that the process of writing data to the stream was after onresultexecuted, so I had to handle response in the Custom responsewrapper stream packaging stream in disguise .)
Effect display
The value of etag (_ etag) is empty when the user first accesses it. The hash calculation result of the generated current content is "s5viknwvqipdyvm46avwn6qq0vg =". In firebug, the returned status is 200, the Response Header has the correct etag value.
Refresh again (do not press Ctrl + F5 to refresh in IE and Firefox; otherwise, the browser will clear the cache and send the request). We can see that the request header contains the etag value, if the page content does not change, the calculated etag value is the same as this value. In Firefox, the HTTP status is 304, And the etag value remains unchanged.
Source code
Actionfilter-contentcachefilterCode
Contentcachefilter
Namespace Sopaco. Lib. Web. MVC. Filters
{
Public Class Contentcachefilter: actionfilterattribute
{
Public Override Void Onactionexecuting (actionexecutingcontext filtercontext)
{
Filtercontext. httpcontext. response. Filter =
New Internaluse. responsewrapper (filtercontext. httpcontext. response. filter,
Filtercontext. httpcontext. Request. headers [ " If-None-match " ]);
}
}
}
Package stream-responsewrapper code:
Responsewrapper
Namespace Sopaco. Lib. Web. MVC. Filters. internaluse
{
Public Class Responsewrapper: Stream
{
# Region Fields
Private Stream _ innerstream;
Private Memorystream _ memstream;
Private String _ Etag = String . Empty;
# Endregion
# RegionConstructors
PublicResponsewrapper (Stream stream,StringEtag)
{
_ Innerstream=Stream;
_ Memstream= NewMemorystream ();
_ Etag=Etag;
}
# Endregion
# Region Properties
Public Byte [] Data
{
Get
{
_ Memstream. Position = 0 ;
Byte [] Data = New Byte [_ Memstream. Length];
_ Memstream. Read (data, 0 ,( Int ) _ Memstream. Length );
Return Data;
}
}
# Endregion
# region overrides of stream class
Public override bool Canread
{< BR> Get { return _ innerstream. canread ;}< BR >}
Public Override BoolCanseek
{
Get{Return_ Innerstream. canseek ;}
}
Public Override BoolCanwrite
{
Get{Return_ Innerstream. canwrite ;}
}
Public Override Void Flush () // There may be such a situation: if the data is large, it may be flush before the transmission ends.
{
VaR httpcontext = Httpcontext. Current;
String Currentetag = Generateetagvalue (data );
If (_ Etag ! = Null )
{
If (Currentetag. Equals (_ etag ))
{
Httpcontext. response. statuscode = 304 ;
Httpcontext. response. statusdescription = " Not modified " ;
Return ;
}
}
Httpcontext. response. cache. setcacheability (httpcacheability. Public );
Httpcontext. response. cache. setetag (currentetag );
Httpcontext. response. cache. setlastmodified (datetime. Now );
Httpcontext. response. cache. setslidingexpiration ( True );
Copystreamtostream (_ memstream, _ innerstream );
_ Innerstream. Flush ();
}
Public Override LongLength
{
Get{Return_ Innerstream. length ;}
}
Public Override Long Position
{
Get
{
Return _ Innerstream. position;
}
Set
{
_ Innerstream. Position = Value;
}
}
Public Override IntRead (Byte[] Buffer,IntOffset,IntCount)
{
Return_ Innerstream. Read (buffer, offset, count );
}
Public Override LongSeek (LongOffset, seekorigin origin)
{
Return_ Innerstream. Seek (offset, origin );
}
Public Override VoidSetlength (LongValue)
{
_ Innerstream. setlength (value );
}
Public override void write ( byte [] buffer, int offset, int count)
{< br> // _ innerstream. write (buffer, offset, count);
_ memstream. write (buffer, offset, count);
}
Public Override VoidClose ()
{
_ Innerstream. Close ();
}
# Endregion
# Region Private helper Methods
Private Void Copystreamtostream (Stream SRC, stream target)
{
SRC. Position = 0 ;
Int Nread = 0 ;
Byte [] Buf = New Byte [ 128 ];
While (Nread = SRC. Read (BUF, 0 , 128 )) ! = 0 )
{
Target. Write (BUF, 0 , Nread );
}
}
Private String Generateetagvalue ( Byte [] Data)
{
VaR encryptor = New System. Security. cryptography. sha1managed ();
Byte [] Encrypteddata = Encryptor. computehash (data );
Return Convert. tobase64string (encrypteddata );
}
# Endregion
}
}
Application Example
[Handleerror]
Public Class Homecontroller: Controller
{
[Contentcachefilter]
// [Lazycachefilter]
Public Actionresult index ()
{
// Viewdata ["message"] = datetime. Now. tostring ();
Viewdata [ " Message " ] = " This is from Asp.net MVC development server " ;
Return View ();
}< P>
Public actionresult about ()
{< br> return View ();
}< BR >}
responsewrapper implementation may be slightly inappropriate, we hope to share more ideas with you.