In the "olden days" of Web Forms, to render an image from the database you would have to create a HttpHandler.
<httpHandlers>
<add verb="GET" path="image.ashx" type="MyApp.Web.ImageHandler, MyApp.Web" validate="false"/>
</httpHandlers>
In ASP.NET MVC you can now use a Controller Action and View to handle an image. One of the benefits is that it can harness the power of System.Web.Routing and there are no web.config sections to maintain.
Step 1 - add a route
routes.MapRoute(
"MyImageHandler",
"image/{id}/{type}.png",
new {controller = "ImageHandler", action = "Image"}
);
Step 2 - create image handling controller
public class FeaturedBusinessesController : Controller
{
public ActionResult Image(string type, Guid id)
{
var myObject = CatalogService.GetMyObject(id);
byte[] imageData = null;
if(type == "large")
{
if(myObject.LargeImage != null)
imageData = myObject.LargeImage.Data;
}
else if(type == "thumb")
{
if(myObject.ThumbImage != null)
imageData = myObject.ThumbImage.Data;
}
if (imageData != null) Response.BinaryWrite(imageData);
return View();
}
}
Step 3 - create the view
<%@ Page Language="C#" ContentType="image/png" AutoEventWireup="true" CodeBehind="Image.aspx.cs" Inherits="MyApp.Web.Views.ImageHandler.Image" %>
NOTE: Notice that the ContentType of the page has been set to "image/png"
Step 4 - render image on your page
The image will now be viewable by going to: /image/8234633b-79b9-4500-a9c8-9b2100c80030/thumb.png
You can change the route however you want and pass in as many parameters to the Image method in order to get the image data back from the database (or any other storage).
Say goodbye to HttpHandlers !???
Technorati Tags:
ASP.NET,
MVC