ASP.NET: images broken when combining URL Rewriting, asp:ImageButton and html base tag
I'm using URL Rewriting under ASP.NET 4 (using ISAPI_Rewrite) and I'm finding that that some of my images are not loading as .NET does not seem to understand I'm using an html BASE tag (pretty standard and essential when doing URL Rewriting):
eg in my development environment I have:
<base href='http://localhost/venuefinder/Website/'></base>
and on my pages I have:
<asp:ImageButton runat="server" ImageUrl="~/images/button.gif" />
On the home page of the site (http://localhost/venuefinder/Website/) this works fine, however on a page that uses URL rewriting, the image does not work:
/venuefinder/Website/venues/ashton_gate_stadium/V18639/
..as the browser is trying to load:
http://localhost/images/buttons/search-button.gif
instead of:
http://localhost/venuefinder/Website/venues/images/buttons/search-button.gif
This is happening because .NET is rendering the button as:
src="../../../images/buttons/search-button.gif"
...which is incorrect.
Is there any way I can correct this problem so that .NET renders the correct src attribute for the开发者_如何学编程 image? (without all the ../../../ etc)
Instead of using ~/
in images, create a virtual folder in IIS called images
which maps to your images directory (so: http://localhost/images
=> c:\myproject\somesubdir\content\images
). Then you can use
<asp:ImageButton runat="server" ImageUrl="/images/button.gif" />
We do this for all our website content items (script / images / css).
If you use <base>
in HTML, the browser takes the given url as base for images that begin with /
. So in your case you can just ditch the tilde.
One of the advantages of the Virtual Directory approach however is that you never have to bother about the url structure again, neither in .NET or JS:
ScriptHelper.RegisterScript("/js/somefile.js")
or
$().append('<img src="/images/file.jpg"/>')
精彩评论