HTTP caching output for .ashx

Im creating an image that has text, for each client the image contains its own name, and I use the Graphics.DrawString function to create this on the fly, however I will not need to create this image more than once, simply because the client’s name is unlikely will change, but I do not want to store it on disk.

Now I create the image in the ie handler:

<asp:Image ID="Image1" runat="server" ImageUrl="~/imagehandler.ashx?contactid=1" /> 

What is the best way to cache the returned image? Should I cache the bitmap that it creates? Or cache the stream I am transmitting? And which cache object should I use, I understand that there are many different ways? But does output caching not work on HTTP handlers? What is the recommended way? (I'm not worried about client side caching, I'm server side) Thanks!

+4
source share
2 answers

The simplest solution I can think of would be to simply cache the Bitmap object in HttpContext.Cache after you created it in the image handler.

 private Bitmap GetContactImage(int contactId, HttpContext context) { string cacheKey = "ContactImage#" + contactId; Bitmap bmp = context.Cache[cacheKey]; if (bmp == null) { // generate your bmp context.Cache[cacheKey] = bmp; } return bmp; } 
+5
source

David,

you can use output caching for the handler. not declaratively, but in code. see if you can use the following snippet.

  TimeSpan refresh = new TimeSpan (0, 0, 15);
 HttpContext.Current.Response.Cache.SetExpires (DateTime.Now.Add (refresh));
 HttpContext.Current.Response.Cache.SetMaxAge (refresh);
 HttpContext.Current.Response.Cache.SetCacheability (HttpCacheability.Server);
 HttpContext.Current.Response.Cache.SetValidUntilExpires (true);

 // try out with - a simple handler which returns the current time

 HttpContext.Current.Response.ContentType = "text / plain";
 HttpContext.Current.Response.Write ("Hello World" + DateTime.Now.ToString ("HH: mm: ss"));
+1
source

All Articles