Tuesday, February 19, 2013

How to Cache image in IHttpHandler?

1. Check header If-Modified-Since, if found, then return Not modified
2. Set Last-Modified header in response header
    public class GetImage : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var If_Modified_Since = context.Request.Headers["If-Modified-Since"];
            if (If_Modified_Since != null)
            {
                context.Response.StatusCode = 304;
                return;
            }
            context.Response.BinaryWrite(Image2Byte(CreateBitmapImage("Hello World")));
            context.Response.Cache.SetMaxAge(new TimeSpan(1, 0, 0)); 
            context.Response.Cache.SetLastModified(System.DateTime.Now);
            context.Response.ContentType = "image";
        }
    }

No comments:

Post a Comment