If you have been developing applications in ASP.NET MVC then you are probably familiar with the ActionResult class. The ActionResult is the most common type of object returned from an action. When building MVC apps, most of time you will use the ActionResult class.

Last week while I was working on my open source project WeBlog, I built an HTTP Handler to serve up images. I started using an HTTP Handler for images because I needed a mechanism to prevent bandwidth leeching. The only bad thing about using an HTTP handler for images is that you end up with some pretty ugly URLS. In my case the URL ended up looking like this:

/Image.axd?image=sample.png

Luckily, my friend Ron noticed my new HTTP Handler and mentioned that I could have accomplished the same thing with a controller action that returned a FileResult instead. After a bit of investigation, I realized that Ron was absolutely right. I deleted my HTTP Handler and replaced it with this code, which was added to the Home Controller:

Since this code resides in my Home controller I would need to use the URL like “/Home/GetImage/sample.png” to display an image. Admittedly this URL is still a big ugly, so I decided to use a custom route to clean it up. The new custom route is named “Images” and is mapped it to the Home controller’s GetImage method. Here is the entry used in the global.asax file:

To the end user, this looks like a traditional file path. However, in reality there is no “Images” folder in the root directory. “Images” is just the name of the route being used. In reality, the image files are actually stored in the App_Data/Images folder.

By using a FileResult object with MVC you not only get a pretty URL but you also get a lot of flexibility on where you want your images to reside. You can store images anywhere you want and the URL will never need to change!