I upgraded my site to use ASP.Net MVC from traditional ASP.Net webforms. I'm using the MVC routing to redirect requests for old .aspx pages to their new Controller/Action equivalent:
routes.MapRoute(
"OldPage",
"oldpage.aspx",
new { controller = "NewController", action = "NewAction", id = "" }
);
This is working great for pages because they map directly to a controller and action. However, my problem is requests for images – I'm not sure how to redirect those incoming requests.
I need to redirect incoming requests for http://www.domain.com/graphics/image.png to http://www.domain.com/content/images/image.png.
What is the correct syntax when using the .MapRoute()
method?
Best Answer
You can't do this "out of the box" with the MVC framework. Remember that there is a difference between Routing and URL-rewriting. Routing is mapping every request to a resource, and the expected resource is a piece of code.
However - the flexibility of the MVC framework allows you to do this with no real problem. By default, when you call
routes.MapRoute()
, it's handling the request with an instance ofMvcRouteHandler()
. You can build a custom handler to handle your image urls.Create a class, maybe called ImageRouteHandler, that implements
IRouteHandler
.Add the mapping to your app like this:
routes.Add("ImagesRoute", new Route("graphics/{filename}",
new ImageRouteHandler()));
That's it.
Here's what your
IRouteHandler
class looks like: