Question
How can I dynamically resize an image in ASP.NET MVC?
Background
I’m trying to automatically create thumbnails from images that are already on the server. In ASP.NET Webforms, I created a HTTPHandler to do this and added verbs in the web.config for all image extensions to pass through the handler. The handler was nice in that if you wanted the original image, you’d use a typical image tag:
<img src="pic.jpg"/>
But if you wanted a resized image, you’d use:
<img src="pic.jpg?width=320&height=240"/>
Is there a way to duplicate the same behavior in ASP.NET MVC?
You can definitely reuse the same
IHttpHandler. You just need a new IRouteHandler to map the incoming request to the correct handler:In your routes, add:
Now any request in
/images(e.g./images/pic.jpg?width=320&height=240) will be handled by your existing handler. Obviously you can change the route pattern to match any path that makes sense, just like a typical MVC route.