Martin de Ruiter
Martin de Ruiter

Reputation: 515

ASP.NET 4 Web forms Routing images

I'm using ASP.NET 4 Web forms routing, for example like this:

routes.MapPageRoute("page-browse", "{Language}/{Label}", "~/Default.aspx")

So the webadress could look like: http://localhost/mywebsite/eng/home

In the root of my website I have a folder "Images".

Image display works when I'm in the root of my website, e.g. by using http://localhost/mywebsite/default.aspx

But when using routing it doesn't work, because the image relative url will look at http://localhost/mywebsite/eng/images instead of http://localhost/mywebsite/images

Is there a way to prevent this using ASP.NET 4 Routing mechanism? Or is the only way to use absolute url's to images?

Upvotes: 1

Views: 3583

Answers (3)

smartcaveman
smartcaveman

Reputation: 42246

  1. Create an IHttpHandler implementation that locates the file's absolute path from the virtual path and renders it as a filestream.

  2. Create an IRouteHandler implementation that returns the http handler I just described if the file has an image extension, or uses the default routing mechanism otherwise.

  3. Register the route handler to be used in the route.

Upvotes: 1

Daniel Ahrnsbrak
Daniel Ahrnsbrak

Reputation: 1077

Two things you could try.

1) Set RouteExistingFiles to false. This will stop routing on any file that the server matches as already existing. Only "virtual" urls that match a route will actually be routed:

routes.RouteExistingFiles = false;

2) Use a StopRoutingHandler route. For example, this would stop routing on all jpgs. You could also set it up to ignore the entire images directory.

routes.Add(new Route("*\.jpg", new StopRoutingHandler()));

Upvotes: 5

Dave Bish
Dave Bish

Reputation: 19646

How are you referencing your images? You should just be able to use a virtual path to the site root, using a prefix of '/' (unless I'm completely misunderstanding the question)

e.g.

<img src="/mywebsite/images/image.jpg" />

Upvotes: 0

Related Questions