缓存HTTP处理程序.ashx的输出

问题描述:

林创造它有它的一些文本,为每一位顾客的图像,图像中包含他们的名字和我用Graphics.DrawString功能来即时创建这一点,但是我不应该需要创建这个形象不止一次,仅仅是因为客户的名字应该很难改变,但我不希望将其存储在磁盘上。

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 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" />

什么是缓存回来图像的最佳方式?我应该缓存它创建位图?或高速缓存我传回的数据流?我应该使用哪个缓存对象,我收集有许多不同的方式?但是,输出缓存不会对HTTP处理程序的工作权利?什么是推荐的方法是什么? (我不在意在客户端缓存,我对有关服务器端)谢谢!

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!

我能想到的是只缓存位图对象在HttpContext.Cache您在图像处理程序创建后,最简单的解决方案。

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;
}