A recent question on Stack Overflow
(and subsequent answer that I wrote for it) inspired this post. I had recently been discussing URL rewriting in depth with my brother, and have also been doing some introductory work with the routing engine in ASP.Net MVC, and the question piqued my interest since I had been meaning to look at this more closely for some time.
The question on Stack Overflow is titled "How do I route images with ASP.Net MVC", but fundamentally the question is really asking "how can I use ASP.Net MVC to re-route URL's to actual physical files, rather than methods of a controller?
To be clear, lets address the conceptual differences between routing and url rewriting. Url rewriting takes the requested URL and modifies it before your code ever sees it. As far as your application is concerned, the client requested the rewritten URL. All that URL rewriting does is to change one URL into another URL, based on pattern matching.
Routing is a different and much more powerful beast. The ASP.Net routing engine maps an URL to a "resource", based on a set of routes. The first route to match the requested URL wins the prize, and sends the request off to the resource it chooses. For the ASP.Net MVC framework (which uses System.Web.Routing under the hood), a resource is something that can handle the request object, which is always a piece of code.
So where does that leave physical files? If a request is always parsed by the routing engine and then handed off to some function somewhere, how can we ever route a request for an image to actually return the physical image?
Well, it takes a tiny bit of legwork, but once we're through it, I'm confident you will see the huge advantages that routing has over simple url-rewriting. We will show the equivalent of url-rewriting by handling a request for an image using an URL that doesn't map to a physical path, but be able to return the image anyway.