Application practice of ASP.net mvc Partial OutputCache in Spacebuilder

Source: Internet
Author: User

Recently to Spacebuilder increased outputcache found some problems, posted here to make a memo, but also easy to encounter similar problems friends check.

The current Spacebuilder presentation layer uses ASP.net MVC v1.0, which uses a lot of renderaction (asp.net of partial mvc, see Requests Partial in Requests MVC). It is hoped that the client-side caching for content areas with low real time requirements will improve performance while also compensating for the loss of renderaction performance.

A scary bug was found using the OutputCache filter with ASP.net mvc, where any one of the Renderaction settings outputcache affects the entire view. Search discovery is indeed a bug currently known to ASP.net mvc, and many people have proposed their own solutions to the problem.

On the cache of ASP.net mvc, Haacked wrote two articles:

Donut Caching in asp.net mvc describes caching the entire page, disabling caching for part of the content, and is the WebForm substitution feature implemented in MVC. There are drawbacks: there are several areas in the current view where it is cumbersome to disable caching, and it is not possible to use different expiration policies for different areas of the page.

Donut Hole Caching in asp.net mvc describes what I want to do, which is to cache only part of the page. But the drawbacks are also obvious: you can only use the user control in the declarative way in WebForm (:), it's a bit out of the way now, and you have to use webformviewengine), you can't use renderpartial directly, and You must also set a strongly typed viewpage to ensure that the model in the user control is the same as the model in view. Too much trouble to use, too many restrictions.

Maarten Balliauw in creating an asp.net mvc OutputCache actionfilterattribute and extending asp.net mvc OutputCache Rattribute-adding substitution also presents a complete outputcache solution. However, when the test enables client-side caching will also produce the same problem with the renderaction, there is no time to thoroughly investigate the issue, the client cache first to disable, temporarily use the server-side cache to cope with a burst.

Based on the code of Maarten Balliauw, the Actionoutputcacheattribute of Spacebuilder was written:

public class Actionoutputcacheattribute:actionfilterattribute


    {


private static MethodInfo _switchwritermethod = typeof (HttpResponse). GetMethod ("Switchwriter", BindingFlags.Instance | BindingFlags.NonPublic);





public actionoutputcacheattribute (int cacheduration)


        {


_cacheduration = cacheduration;


        }





//Is not currently set to the client cache and will have the same problem as OutputCache


private CachePolicy _cachepolicy = Cachepolicy.server;


private int _cacheduration;


private TextWriter _originalwriter;


private String _cachekey;





public override void OnActionExecuting (ActionExecutingContext filtercontext)


        {


//Server-side caching?


if (_cachepolicy = = Cachepolicy.server | | _cachepolicy = = cachepolicy.clientandserver)


            {


_cachekey = Generatecachekey (Filtercontext);


Cachecontainer cachedoutput = (cachecontainer) Filtercontext.httpcontext.cache[_cachekey];


if (cachedoutput!= null)


                {


filterContext.HttpContext.Response.ContentType = Cachedoutput.contenttype;


Filtercontext.result = new Contentresult {Content = cachedoutput.output};


                }


Else


                {


StringWriter StringWriter = new Stringwriterwithencoding (filterContext.HttpContext.Response.Con tentencoding);


HtmlTextWriter newwriter = new HtmlTextWriter (StringWriter);


_originalwriter = (TextWriter) _switchwritermethod.invoke (HttpContext.Current.Response, New objec T[] {newwriter});


                }


            }


        }





public override void Onresultexecuted (ResultExecutedContext filtercontext)


        {


//Server-side caching?


if (_cachepolicy = = Cachepolicy.server | | _cachepolicy = = cachepolicy.clientandserver)


            {


if (_originalwriter!= null)//must complete the caching


                {


HtmlTextWriter cachewriter = (HtmlTextWriter) _switchwritermethod.invoke (HttpContext.Current.Res Ponse, new object[] {_originalwriter});


string textwritten = ((StringWriter) cachewriter.innerwriter). ToString ();


FilterContext.HttpContext.Response.Write (Textwritten);


Cachecontainer container = new Cachecontainer (Textwritten, FilterContext.HttpContext.Response.Co Ntenttype);


filterContext.HttpContext.Cache.Add (_cachekey, container, NULL, DateTime.Now.AddSeconds (_cachedu Ration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, NULL);


                }


            }


        }





private String Generatecachekey (ActionExecutingContext filtercontext)


        {


StringBuilder cachekey = new StringBuilder ("Outputcachekey:");





//Controller + action


Cachekey.append (FilterContext.Controller.GetType (). Fullname.gethashcode ());


if (FilterContext.RouteData.Values.ContainsKey ("Action"))


            {


Cachekey.append ("_");


Cachekey.append (filtercontext.routedata.values["action"). ToString ());


            }





foreach (keyvaluepair<string, object> pair in filtercontext.actionparameters)


            {


Cachekey.append ("_");


Cachekey.append (pair. Key);


cachekey.append ("=");





if (pair. Value!= null)


Cachekey.append (pair. Value.tostring ());


Else


cachekey.append (String. Empty);


            }





return cachekey.tostring ();


        }





Private Class Cachecontainer


        {


public string Output;


public string ContentType;


public Cachecontainer (string data, string contentType)


            {


Output = data;


ContentType = ContentType;


            }


        }





public enum CachePolicy


        {


nocache = 0,


Client = 1,


Server = 2,


Clientandserver = 3


        }


    }





     {


encoding;

Stringwriterwithencoding

public class StringWriterWithEncoding : StringWriter
    {
        Encoding encoding;
        public StringWriterWithEncoding(Encoding encoding)
        {
            this.encoding = encoding;
        }
        public override Encoding Encoding
        {
            get { return encoding; }
        }
}

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.