How to Route Images Using ASP.NET MVC Routing

How do I route images using ASP.Net MVC routing?

You can't do this "out of the box" with the MVC framework. Remember that there is a difference between Routing and URL-rewriting. Routing is mapping every request to a resource, and the expected resource is a piece of code.

However - the flexibility of the MVC framework allows you to do this with no real problem. By default, when you call routes.MapRoute(), it's handling the request with an instance of MvcRouteHandler(). You can build a custom handler to handle your image urls.

  1. Create a class, maybe called ImageRouteHandler, that implements IRouteHandler.

  2. Add the mapping to your app like this:

    routes.Add("ImagesRoute", new Route("graphics/{filename}",

    new ImageRouteHandler()));

  3. That's it.

Here's what your IRouteHandler class looks like:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.Routing;
using System.Web.UI;

namespace MvcApplication1
{
public class ImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string filename = requestContext.RouteData.Values["filename"] as string;

if (string.IsNullOrEmpty(filename))
{
// return a 404 HttpHandler here
}
else
{
requestContext.HttpContext.Response.Clear();
requestContext.HttpContext.Response.ContentType = GetContentType(requestContext.HttpContext.Request.Url.ToString());

// find physical path to image here.
string filepath = requestContext.HttpContext.Server.MapPath("~/test.jpg");

requestContext.HttpContext.Response.WriteFile(filepath);
requestContext.HttpContext.Response.End();

}
return null;
}

private static string GetContentType(String path)
{
switch (Path.GetExtension(path))
{
case ".bmp": return "Image/bmp";
case ".gif": return "Image/gif";
case ".jpg": return "Image/jpeg";
case ".png": return "Image/png";
default: break;
}
return "";
}
}
}

ASP.net MVC Image Routing

What order is the route in your route mappings?

MVC matches the FIRST matching route, not the most specific, I'd guess that you're hitting your default route before you images specific route.

I suspect if you're trying to hit "Images/Myfile.png" what's happening is that the route is trying to find a static file rather than using your image route.

Perhaps have a look through other questions such as this for further info:

Routing a url with extension in MVC4 won't work, tries to serve up static file

How do I route images through ASP.NET routing?

Thats how asp.net routing works, there is no away around that... you have to use Rewrite if you want to intercept requests for existing files.

Update

Seems like i was a bit too fast on the trigger there. There seems to be a property you can set which allows you to enforce a route even for existing files.

RouteCollection.RouteExistingFiles Property

http://msdn.microsoft.com/en-us/library/system.web.routing.routecollection.routeexistingfiles.aspx

Gets or sets a value that indicates whether ASP.NET routing should handle URLs that match an existing file. True if ASP.NET routing handles all requests, even those that match an existing file; otherwise, false. The default value is false.

ASP.NET 4 - url routing for images

Try something like this:

Route:

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

Controller:

public ActionResult Images(string file)
{
path = "/Projects/test/images/" + file;
if (!System.IO.File.Exists(path))
{
return new HttpNotFoundResult();
}

return File(path, "image/jpeg");
}

ASP.NET custom routes breaking images and javascript

The slug is being treated as a directory. You would need to add an extra ../ to the image path for it to work when the url contains a slug. You should really avoid using relative paths like that on your website.

How to fix it so that it works on every page

You could change it to use a path that is relative to the site root like so:

<img src="/Content/images/picture.jpg" alt="" height="42" width="37" />

Or you could use a helper method that is available with asp.net mvc, it works like this. This method will auto-magically translate the path relative to the current url.

<img src="@Url.Content("~/Content/images/picture.jpg")" ... />

This will work with <script> and <link> tags as well as any other tag which references a url.

NOTE: I am using Razor syntax above, if you are using the web forms view engine the code would look like this.

<img src="<%: Url.Content("~/Content/images/picture.jpg") %>" ... />

Additional note, I feel dirty having just written the <% %> tags after having used razor for a few months.

Route images in View folder in Asp.Net MVC 3

Using this route:

routes.MapRoute(
"Parameter",
"{controller}/{action}/{lang}/{prod}",
new { controller = "Manuals", action = "Product", lang = "en-US", prod = "name" }
);

Create this action in your controller ManualsController

public ActionResult Product(string lang,string prod){
var root = Server.MapPath("~/views/manuals/");
var filepath = Path.Combine(root,lang,prod,".svg"); // whatever creates your path here.
return File(filepath ,"your mime type");
}

No need for a custom view engine. The FileResult is designed for just this occasion.



Related Topics



Leave a reply



Submit