Caching (Cache) ~ Third back HttpModule implementing file-level caching for Web pages

Source: Internet
Author: User
Tags file url

Back to Catalog

Write the first time after the cache, got a lot of friends and letters, so decided to speed up the pace, as soon as possible to finish the rest of the article, this is the third, the main introduction of the use of HttpModule implementation of the file-level cache, before looking at this article, we need to limit HttpModule have an understanding, You can read my article first. "Developers should know more about the knowledge of the IIS theory layer ~ IV" several major events in HttpModule

For file-level caching, we need to know two points, one for the file URL, two for the file

Here is the core code of Httpmodulecache

/// <summary>    ///Cachehttpmodule class/// </summary>    Internal classCachehttpmodule:ihttpmodule { Public voidDispose () {}Privatelist<string>Listneedcacheextend; Private stringStringclearcache ="Zzl";//The first URL in the domain name, if this character, indicates that the request is clear cache such as:http://www.domain.com/zzl/*******         Public voidInit (HttpApplication context) {context. BeginRequest+=NewEventHandler (context_beginrequest); Context. ReleaseRequestState+=NewEventHandler (context_releaserequeststate); Listneedcacheextend=Newlist<string>(); stringextends = Webconfig.getusersection ("Cacheinfo","Extendtypes",". html|. HTM"); foreach(stringSinchExtends. Split ('|'))            {                if(!string. IsNullOrEmpty (s) &&!Listneedcacheextend.contains (S.trim ())) Listneedcacheextend.add (S.trim ()); }        }         Public voidContext_beginrequest (Objectsender, EventArgs e) {            varApplication =(HttpApplication) sender; if(Isneedcache (application))//detects whether the current request requires caching            {                stringKey =string.                Empty;; stringExtend =virtualpathutility.getextension (Application. Context.Request.FilePath).                ToLower (); if(Isclearcache (Application, outkey)) {                    if(Cachemanage.container (key, Extend))//cache exists, clears the cache, ends the request{application.                    Context.Response.Write (Cachemanage.remove (key, extend));                } application.completerequest (); }                Else                {                    #regionUsing page compressionResponsecompressiontype Compressiontype= This. Getcompressionmode (Application.                    Context.request); if(Compressiontype! =responsecompressiontype.none) {application. Context.Response.AppendHeader ("content-encoding", Compressiontype.tostring ().                        ToLower ()); if(Compressiontype = =responsecompressiontype.gzip) {application. Context.Response.Filter=NewGZipStream (Application.                        Context.Response.Filter, compressionmode.compress); }                        Else{application. Context.Response.Filter=NewDeflatestream (Application.                        Context.Response.Filter, compressionmode.compress); }                    }                    #endregion                    if(Cachemanage.container (key, Extend))//is present in the cache, the content is returned directly, ending the request{cachemanage.write (application, key);                    Application.completerequest (); }                }            }        }        /// <summary>        ///detects whether the current request needs to be cached, and if so, adds the result to the cache, and if this request is faulted, it will not be executed ./// </summary>        /// <param name= "Sender" ></param>        /// <param name= "E" ></param>         Public voidContext_releaserequeststate (Objectsender, EventArgs e) {            varApplication =(HttpApplication) sender; if(Application. Context.Response.StatusCode = = $)            {                stringSTRT =NULL; stringExtend =virtualpathutility.getextension (Application. Context.Request.FilePath).                ToLower (); if(Isneedcache (application) &&! Isclearcache (Application, outstrt)) {                    stringKey =application.                    Context.Request.Url.AbsoluteUri; //If you need to add a cache,                    if(!Cachemanage.container (key, Extend)) {Application. Context.Response.Filter=Newresponsefilter (Application. Context.Response.Filter, key, extend, application.                    Context.Response.ContentEncoding); }                }            }        }         Public voidContext_endrequest (Objectsender, EventArgs e) {            varApplication =(HttpApplication) sender; stringKey =application.            Context.Request.Url.AbsoluteUri; Application. Context.Response.Write ("<br>cachemdule EndRequest"); }        /// <summary>        ///detects the current request type (URL extension) to determine if caching is required///if the type needs to be cached, but the extension is HTML or HTM and the corresponding physical file exists, the cache operation is not performed/// </summary>        /// <param name= "strFilePath" ></param>        /// <returns></returns>        Private BOOLIsneedcache (HttpApplication application) {BOOLBoolneedcache =false; stringStringextend =virtualpathutility.getextension (Application. Context.Request.FilePath).            ToLower (); if(NULL! = listneedcacheextend)//whether the URL extension meets the criteria{Boolneedcache=Listneedcacheextend.contains (stringextend); }            if(boolneedcache) {if(Stringextend = =". html"|| Stringextend = =". htm")                {                    if(System.IO.File.Exists (Application. Context.Request.PhysicalPath))//The corresponding physical file exists{Boolneedcache=false; }                }            }            returnBoolneedcache; }        /// <summary>        ///detects if the cache is cleared for the time of the request///True to clear cache False not to clear cached/// </summary>        /// <param name= "Application" ></param>        /// <param name= "url" >a real URL address</param>        /// <returns></returns>        Private BOOLIsclearcache (HttpApplication application, out stringURL) {            BOOLBoolclearcache =false; URL=application.            Context.Request.Url.AbsoluteUri; stringDomain =application.            Context.Request.Url.Host; Regex regex=NewRegex ("/ http"+ domain +"/"+ Stringclearcache +"/", Regexoptions.singleline | regexoptions.compiled |regexoptions.ignorecase); if(regex.) IsMatch (URL)) {Boolclearcache=true; URL="/ http"+ domain +"/"+ URL. Replace (regex. Match (URL). captures[0]. Value,string.            Empty); }            returnBoolclearcache; }        /// <summary>        ///get the compression type supported by the client/// </summary>        /// <param name= "Request" ></param>        /// <returns></returns>        Privateresponsecompressiontype Getcompressionmode (System.Web.HttpRequest request) {stringacceptencoding = Request. headers["accept-encoding"]; if(string. IsNullOrEmpty (acceptencoding))returnResponsecompressiontype.none; Acceptencoding=acceptencoding.toupperinvariant (); if(Acceptencoding.contains ("GZIP"))                returnResponsecompressiontype.gzip; Else if(Acceptencoding.contains ("DEFLATE"))                returnresponsecompressiontype.deflate; Else                returnResponsecompressiontype.none; }        Private enumResponsecompressiontype {None, GZip, Deflate}}

For the above HttpModule, you also need to configure the config file in the appropriate configuration, the code is as follows

<modules runallmanagedmodulesforallrequests="true" >      <add name=" Cachehttpmodule " type="httpmodulecache.cachehttpmodule,httpmodulecache"/>    </ Modules>

After the program is run, when a legitimate file is detected (such as before you cache HTML and shtml files), the file will be generated to the server at the specified location, the next time you visit, directly through the URL generated by the server local path, the static file will be returned to the client, but there is a place to note, Because this method generates a cache file, its location is not fixed, so when referencing css,js such a file, it is used in the form of an absolute path.

When no absolute path is used

After using the absolute path

How, this kind of file-level cache of the way everyone has mastered it!

Download the full Httpmodulecache project

Back to Catalog

Caching (Cache) ~ Third back HttpModule implementing file-level caching for Web pages

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.