1

I have created an ImageController to serve images from a location in my project. Now I'm trying to get it to route from "/Image/file.png" to my Controller, but I can't seem to get it right. The controller is never been called (I set a breakpoint in the first line of the action and it never breaks).

My route:

routes.MapRoute(
            "Image",
            "Image/{file}",
            new { controller = "Image", action = "Render", file = "" }
        );

My ImageController:

public class ImageController : Controller
{
    //
    // GET: /Image/

    public ActionResult Render(string file)
    {
        var path = this.getPath(file);
        System.Diagnostics.Debug.WriteLine(path);
        if (!System.IO.File.Exists(path))
        {
            return new HttpNotFoundResult(string.Format("File {0} not found.", path));
        }
        return new ImageResult(path);
    }

    private string getPath(string file)
    {
        return string.Format("{0}/{1}", Server.MapPath("~/Content/Images"), file);
    }
}

Why isn't my project routing from "Images/{file}" to my controller?

Scuba Kay
  • 2,004
  • 3
  • 26
  • 48
  • This might be helpful: http://stackoverflow.com/questions/11257768/asp-net-mvc-route-bypass-staticfile-handler-for-path . From Scott's article, you might be able to put a *.png, *.gif, *.jpg wild card for a handler to process those requests. – TSmith Oct 25 '13 at 14:54

1 Answers1

1

It's probably because the request is being routed to the static file handler due to the .png extension in the url. You could try passing the filename and suffix as separate parameters, something like this:

routes.MapRoute(
        "Image",
        "Image/{filename}/{suffix}",
        new { controller = "Image", action = "Render", filename = "", suffix = "" }
);

Your controller action then becomes:

public ActionResult Render(string filename, string suffix)

And it should match urls like this:

/Image/file/png
levelnis
  • 7,665
  • 6
  • 37
  • 61