My thoughts regarding ASP.NET, C#, programming practices, and more...
reading
You Should Read archives
blogs I read
|
Saturday, May 28, 2005Alternative to ApplicationPath
For some time now I have been fighting a battle that I thought I might never win. But once again the ASP.NET community comes through again with the following blog posting.
Problem I develop most of my websites locally on my Windows XP machine using it's native IIS. This means that I use relative paths. When creating user controls that I will be utilizing on pages throughout the site I may need to reference the Response.ApplicationPath property for an image tag or when calling Response.Redirect(). The code would look something like this: <img src="<%= Response.ApplicationPath %>/images/spacer.gif" /> This method works great until I push the website form my local machine to the staging server running Windows 2003. Suddenly anywhere I am using Response.ApplicationPath, I recieve a 404, "File Not Found" error. The reason being that while my website was hosted on my local machine, it lay in a sub-directory of one Default Website. However, on the staging server, it lies in the root directory of it's own website. This meant that on my local box a backslash was required after the Response.Application, but on the staging server, I had to remove the backslash. Solution Place the following code in the Application_BeginRequest event handler of the Global.asax file: // Build the Application Path This code should only run once and only if if the Application variable becomse null. Using the above code you should no longer have to worry about those moves from your local machine to staging or production web servers. Update 06/30/2005: See also Making Sense of ASP.Net Paths by Rick Strahl
Comments:
Content copyright ©2003-2006 Tod Birdsall
Doesn't the squiggle work in this case too? For instance, < img runat=server src="~/images/spacer.gif" / >?
It makes sense to me that it would since ASP.NET internal controls support the ~ as an application path designator wherever you can provide a link, but it seems that you have to set the path via the code behind file. Your example wouldn't work, but if you set the Src in the code behind like this:
Post a Comment
myImg.Src = "~/images/door2.gif"; That works. Links to this post: << Home |