简体   繁体   English

缓存http处理程序.ashx输出

[英]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 of the customer should hardly change, but I do not want to store it on disk. 我创建了一个包含一些文本的图像,对于每个客户,图像都包含它们的名称,我使用Graphics.DrawString函数动态创建它,但是我不需要多次创建这个图像,只是因为客户名称几乎不会改变,但我不想将其存储在磁盘上。

Now I am creating the image in a handler ie : 现在我在处理程序中创建图像,即:

<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? 但输出缓存对http处理程序不起作用吗? 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. 我能想到的最简单的解决方案是在你在图像处理程序中创建它之后,将Bitmap对象缓存在HttpContext.Cache中。

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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM