Image Handler in ASP.NET WebForms and MVC

Image handlers allow your application to enforce policy or apply business logic before serving up the image. For example you may want to do one of the following:

  • Enforce authorization based upon user credentials / roles to limit access to images. This for instance can be used to prevent unauthorized access / downloads of images.
  • Dynamically create and serve a thumbnail when the user request a full size image.
  • Add an overlay (e.g. copyright watermark) on the image in memory before serving it back to the browser.

Image handlers can perform these and many other functions. This blog will discuss two implementations for an image handler. The first will be an ASP.NET HttpHandler. The second will be an MVC controller implementation.

HttpHandler Implementation

An HttpHandler is a process that is run in response to a request made to an ASP.NET web application. The most common HttpHandler is the handler that processes requests for .aspx files. To create an HttpHandler you implement the IHttpHandler interface. Here is a simple image handler:

public class Image : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
        // Authenticate user.
        //
        if (!context.User.IsInRole("Admin"))
        {
            return;
        }

        // Get the image id.
        //
        string idString = context.Request.Params["id"];
        if (string.IsNullOrEmpty(imageRelativePath))
        {
            return;
        }

        // Determine if the image is being downloaded and saved
        //    or streamed back into the response.
        //
        bool isDownload = false;
        if (context.Request.Params["d"] != null)
        {
            isDownload = true;
        }

        // Fetch the image.
        //
        string imageFullPath = ImageService.FetchImagePath(idString);
        System.Drawing.Image image = System.Drawing.Image.FromFile(imageFullPath);
        if (image == null)
        {
            return;
        }

        // ************
        // Insert processing here.
        // ************
        //
        image = AddCopyrightOverlay(image);

        if (isDownload)
        {
            context.Response.AddHeader(
                "Content-Disposition",
                "attachment; filename="
                + Path.GetFileName(imageFullPath));
        }
        context.Response.ContentType = "Image/jpeg";
        image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        context.Response.End();
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

This code first enforces authorization by validating the user belongs to the ‘Admin’ role. Next the the query string parameters are parsed and validated. Next the image path is fetched and the image is loaded into an .NET Image object. A copyright overlay is then added to the image. Finally, the image is streamed back to the browser.

This code handles request of the form:

  • http://URL…/Image.ashx?id=xyz
  • http://URL…/Image.ashx?id=xyz&d=true

In this case, the ‘id’ parameter is required and the value ‘xyz’ is the image ID. The ‘d’ parameter is optional and allows the same image handler to be used to download and save images.

MVC Controller

The ASP.NET MVC routing allows image requests to be handled by a controller. The following is a simple controller that provides image handler functionality:

public class ImageController : Controller
{
    [Authorize(Roles="Admin")]
    public ActionResult Thumb(Guid imageId)
    {
        Bitmap bitmap = ImageHelper.FetchImage(imageId);
        if (bitmap == null)
        {
            return new EmptyResult();
        }

        MemoryStream ms = new MemoryStream();
        bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.Seek(0, SeekOrigin.Begin);
        FileStreamResult fileStreamResult = new FileStreamResult(ms, "image/png");
        return fileStreamResult;
    }
}

This controller has a Thumb action that returns a thumbnail of an image given an image ID. Authorization is provided using the MVC “Authorize” attribute configured to allow access to only users in the “Admin” role. The image is fetched from a repository and then streamed back to the browser.

The image can then be requested with the following URL.

  • http://URL…/Image/Thumb?imageId=GUID

In this case the ASP.NET MVC routing will map the query string parameter ‘imageId’ to the Thumb action’s input parameter. The GUID value must obviously be able to be converted to into a .NET Guid type.

Summary

Both of the image handlers will allow you to inject policy or business logic into an image request before the server responds. One advantage of the HttpHandler solution is that it can be configured in the Web.Config file to handle all requests with a certain path (*.jpg for instance). The HttpHandler is also a bit closer to the request in terms of the ASP.NET pipeline. This may also be an advantage. Be sure that your images aren’t directly accessible via a direct URL.

Comments
  1. web designing Agra

Leave a Reply to web designing Agra Cancel reply

Your email address will not be published.

*