2

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.

1 Answer 1

2

I have not found a perfect solution to this, but have a compromise. I simply couldn't get the routes to work without the {controller} aspect. So what I've done in the end is add a new route:

        routes.MapRoute(
            "FileProvider",
            "{controller}/{action}/{id}/{name}",
            new { controller = "File", action = "GetFile", id = UrlParameter.Optional },
            new[] { "mynamespace.Controllers" }
        );

This allows routes to my Controller > FileController > GetFile method, e.g.

    public FileResult GetFile(int id, string name)
    {
        DB.UploadedFile file;

        file = DB.UploadedFile.GetFile(4, DB.UploadedFile.UploadedFileType.IMAGE, id, name);

        if (file != null && DB.UploadedFile.IsImage(file.Filename))
        {
            ImageFormat imgFormat = GetImageFormat(file.Extension);

            if (imgFormat != ImageFormat.Icon)
            {
                return File(file.FileContentsAsByteArray, file.ContentType);
            }
        }
        return null;
    }

So this allows me to serve an image such as:

http://mydomain.com/File/GetFile/1/DogsAndCats

The code makes sure that the id and name matches so that people can't just search through the database of files.

There's no extension to the file at the moment, which may cause issues, but so far - as long as the content type is set) then the image loads correctly.

There's more work to be done in my code to serve other file types, but perhaps this compromise will be useful for others.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.