Created
January 15, 2013 11:50
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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