开发者

Caching http handler .ashx output

Im creating an image which has some text in it, for every customer, the image contains their name and I use the Graphics.DrawString function to create this on the fly, however I should not need to create this image more than once, simply because the name开发者_StackOverflow of the customer should hardly change, but I do not want to store it on disk.

Now I am creating the image in a handler i.e :

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

What is the best way to cache the image that comes back? Should I cache the bitmap it creates? Or cache the stream that I pass back? And which cache object should I use, I gather there are many different ways? But output caching doesn't work on http handlers right? What is the recommended way? (I'm not bothered about caching on client side, I'm on about server side) Thanks!


The simplest solution I can think of would be to just cache the Bitmap object in the HttpContext.Cache after you've 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;
}


David,

you can use output caching on handler. not declaratively but in code behind. see if you can use 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"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜