C# ASP.NET MVC2 Routing Generic Handler
Maybe I am searching the wrong thing or trying t开发者_Go百科o 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.
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.
I use that solution for a long time now, you can make it generic so it will accept any handler you'll have in the future:
internal class RouteGenericHandler<T> : IRouteHandler where T : IHttpHandler, new()
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new T();
}
}
And on RegisterRoutes method:
routes.Add(new Route("Name", new RouteGenericHandler<TestHandler>()));
精彩评论