views:

31

answers:

1

Hi,

Maybe I am searching the wrong thing or trying to implement this the wrong way. I am dynamically generating an image using a Generic Handler. I can currently access my handler using:

ImageHandler.ashx?width=x&height=y

I would much rather access my handler using something like

images/width/height/imagehandler

Is this possible the few examples I found on google didn't work with MVC2.

Cheers.

A: 

I continued working on this problem last night and to my surprise I was closer to the solution that I had thought. For anyone who may struggle with this in the future here is how I implemented MVC2 Routing to a Generic Handler.

First I created a class that inherited IRouteHandler

public class ImageHandlerRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var handler = new ImageHandler();
        handler.ProcessRequest(requestContext);

        return handler;
    }
}

I then implemented the generic handler creating an MVC friendly ProcessRequest.

public void ProcessRequest(RequestContext requestContext)
{
    var response = requestContext.HttpContext.Response;
    var request = requestContext.HttpContext.Request;

    int width = 100;
    if(requestContext.RouteData.Values["width"] != null)
    {
        width = int.Parse(requestContext.RouteData.Values["width"].ToString());
    }

    ...

    response.ContentType = "image/png";
    response.BinaryWrite(buffer);
    response.Flush();
}

Then added a route to the global.asax

RouteTable.Routes.Add(
    new Route(
        "images/{width}/{height}/imagehandler.png", 
        new ImageShadowRouteHandler()
    )
 );

then you can call your handler using

<img src="/images/100/140/imagehandler.png" />

I used the generic handler to generate dynamic watermarks when required. Hopefully this helps others out.

If you have any questions let me know and I will try and help you where possible.

Daniel Draper