Skip to content

Instantly share code, notes, and snippets.

@frankgeerlings
Created January 15, 2013 11:50
Show Gist options
  • Save frankgeerlings/4538102 to your computer and use it in GitHub Desktop.
Save frankgeerlings/4538102 to your computer and use it in GitHub Desktop.
Handle images yourself (minimal implementation, add logic you might need here) — works on ASP.NET MVC as well as WebForms.
using System;
using System.Linq;
using System.Web;
public class ImageHttpHandler : IHttpHandler
{
21public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
var response = context.Response;
var request = context.Request;
var physicalFilePath = request.MapPath(request.Path);
AddCachingHeadersToResponse(physicalFilePath, response);
response.Clear();
response.ContentType = GetContentType(physicalFilePath);
response.TransmitFile(physicalFilePath);
}
private static void AddCachingHeadersToResponse(string physicalFilePath, HttpResponse response)
{
response.AddFileDependency(physicalFilePath);
response.Cache.SetETagFromFileDependencies();
response.Cache.SetLastModifiedFromFileDependencies();
response.Cache.SetCacheability(HttpCacheability.Public);
response.Cache.SetExpires(DateTime.Now.AddMonths(1));
response.Cache.SetMaxAge(new TimeSpan(30));
response.Cache.SetSlidingExpiration(true);
response.Cache.SetValidUntilExpires(true);
response.Cache.VaryByParams["*"] = true;
}
private static string GetContentType(string physicalFilePath)
{
var extension = physicalFilePath.Split('.').DefaultIfEmpty(string.Empty).Last().ToLowerInvariant();
switch (extension)
{
case "jpg":
case "jpeg":
return "image/jpeg";
case "png":
return "image/png";
case "gif":
return "image/gif";
default:
return "application/octet-stream";
}
}
}
<configuration>
<system.web>
<httpHandlers>
<add verb="GET,HEAD" path="*.jpg" type="Website.Handlers.ImageHttpHandler,Website" />
<add verb="GET,HEAD" path="*.gif" type="Website.Handlers.ImageHttpHandler,Website" />
<add verb="GET,HEAD" path="*.png" type="Website.Handlers.ImageHttpHandler,Website" />
</httpHandlers>
</system.web>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment