title: MVC Image Handler with Url rewrite
body: <p>I'm attempting to be able to build a handler which serves back images in a friendly way, e.g. <a href="http://mydomain.com/images/123/myimage.jpg" rel="nofollow">http://mydomain.com/images/123/myimage.jpg</a> or even .../123/myimage</p>
  
  <p>I have previous done this before using .NET Forms and an ashx file.</p>
  
  <p>I'm now using MVC 4 (Which I am new to) and am attempting to do the same thing. I re-used a lot of my old code and added an ashx file to my project and passed through querystrings to successfully generate my image. However, I just cannot get the Url Rewrite to work!</p>
  
  <p>In my old code I used:</p>
  
  <pre><code>        RouteTable.Routes.MapHttpHandlerRoute("imagestoret", "imagestore/{fileId}", "~/Images/ImageHandler.ashx");
          RouteTable.Routes.Add(new Route("imagestore/{fileId}", new PageRouteHandler("~/Images/ImageHandler.ashx")));
  </code></pre>
  
  <p>Where MapHttpHandlerRoute is a custom class found on the internet containing:</p>
  
  <pre><code>    public IHttpHandler GetHttpHandler(RequestContext requestContext)
      {
          if (!string.IsNullOrEmpty(_virtualPath))
          {
              return (IHttpHandler)System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(IHttpHandler));
          }
          else
          {
              throw new InvalidOperationException("HttpHandlerRoute threw an error because the virtual path to the HttpHandler is null or empty.");
          }
      }
  </code></pre>
  
  <p>Since then I have tried converting it into a Controller which worked successfully with a querystring, however, when I tried to add the routing in it still returns a 404 error.</p>
  
  <pre><code>routes.MapRoute(
              "ImageProvider",
              "imagestore/{fileId}/",
              new { controller = "File", action = "GetFile", id = UrlParameter.Optional });
  </code></pre>
  
  <p>I have also tried an ImageRouteHandler from the internet:</p>
  
  <pre><code>    public class ImageRouteHandler : IRouteHandler
  {
      public IHttpHandler GetHttpHandler(RequestContext requestContext)
      {
          // Do stuff
      }
  }
  </code></pre>
  
  <p>And then adding the following into my RouteConfig.cs:</p>
  
  <pre><code>        routes.Add("MyImageHandler",
              new Route("imagex/{fileId}",
              new ImageRouteHandler())
          );
  </code></pre>
  
  <p>Does anyone know where I'm going wrong?</p>
  
  <p>Thanks in advance.</p>