I'm attempting to be able to build a handler which serves back images in a friendly way, e.g. http://mydomain.com/images/123/myimage.jpg or even .../123/myimage
I have previous done this before using .NET Forms and an ashx file.
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!
In my old code I used:
RouteTable.Routes.MapHttpHandlerRoute("imagestoret", "imagestore/{fileId}", "~/Images/ImageHandler.ashx");
RouteTable.Routes.Add(new Route("imagestore/{fileId}", new PageRouteHandler("~/Images/ImageHandler.ashx")));
Where MapHttpHandlerRoute is a custom class found on the internet containing:
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.");
}
}
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.
routes.MapRoute(
"ImageProvider",
"imagestore/{fileId}/",
new { controller = "File", action = "GetFile", id = UrlParameter.Optional });
I have also tried an ImageRouteHandler from the internet:
public class ImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
// Do stuff
}
}
And then adding the following into my RouteConfig.cs:
routes.Add("MyImageHandler",
new Route("imagex/{fileId}",
new ImageRouteHandler())
);
Does anyone know where I'm going wrong?
Thanks in advance.