Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving Images from same routed URL path in ASP.NET MVC

Here's what I'd like to do. I have content that I am writing out to a view. This content has image references that are document relative. So for example, if I'm looking at the following URL:

http://localhost/article/8AB98/

The content might have an image in the following form:

<img src="myimage.png" />

This would obviously cause the browser to query for the image at the following URL:

http://localhost/article/8AB98/myimage.png

However, because of the mvc routing, this image would not be found. Do you know of a simple way that I can cause that URL to return the correct image to the browser?

please note: it's actually important that the markup remain untouched from the original ... this means that somehow re-writing image urls so they point to another folder outside of the current view's URL is unfortunately out of the question.

Thanks!!

like image 611
Joel Martinez Avatar asked Aug 08 '09 03:08

Joel Martinez


2 Answers

You can use the Url.Content() method.

<img src="<%= Url.Content("~/images/myimage.png") %>" />

That will resolve the url from the application root.

like image 117
Haacked Avatar answered Oct 23 '22 14:10

Haacked


I'm assuming that when you say "it's actually important that the markup remain untouched from the original" you mean that

<img src="myimage.png" />

is what must be rendered to the browser and so you need to trick the web server into taking the request URL of

http://localhost/article/8AB98/myimage.png

and use only that information to find the correct image, wherever you have it stored, and return it to the browser.

Two options come to mind, but it's hard to know which to recommend because you haven't said where the images are being stored.

Option 1 - Url Rewriter

Buy a copy of ISAPI_Rewrite and have all urls that meet the above criteria rewritten so that they go get the image wherever it lives. More on ISAPI_Rewrite here.

Option 2 - Custom HttpHandler

You could write an HttpHandler mapped to all PNG file requests that parses the request URL and does what it needs to do to find the image, then return it to the response stream. The downside of this is that you'd have to tell IIS to map all PNG requests to go through the aspnet_isapi.dll which might be a performance bummer.

I'm still not sure if I understand your problem correctly but I hope this helps. Good luck.

like image 36
JamieGaines Avatar answered Oct 23 '22 14:10

JamieGaines