ASP.Net Application Path Woes
.Net Development, ASP.NET, Application Paths, Development No Comments »ASP.Net has various objects, properties, and methods manipulating and obtaining URL path information. I did a search on Google for "asp.net paths". Rick Strahl's Web log had a nice breakdown of some of the common approaches for obtaining path information. Reading through the threads that were posted at the end of his article made my head spin. I thought, "There's got to be a simple property built into ASP.Net Framework for obtaining the root Url path for a Web application."
After a lot of digging around on-line, I did not discover any built-in ASP.NET
functionality that would return a fully qualified domain name Uri for an
ASP.Net application.
I wrote some test code and iterated through some scenarios. I discovered that the tilda "~" in front of Urls and HttpContext.Request.ApplicationPath both have problems and do not work in all usage scenarios. (i.e. Application hosted off the root of a Web site, certain scenarios involving the use of "#" in Anchor tags in User controls, etc).
Conclusion: I will have to create my own bullet-proof methodology for generating Url paths for various links in ASP.Net applications. I decided to write a simple class for this purpose, so it would be easy to use. The class is called App. Inserting it into the root of your Web project makes generating Urls simple and painless.
The Urls generated are not relative. Each one is generated using the fully qualified domain name of the application instance, so paths always resolve properly. (i.e. http://myapp/someFolder/someResource.aspx)
Here's some sample usage scenarios:
Url Redirection
Response.Redirect(App.Url + "/SomeFolder/SomePage.aspx" + "?idValue="
+ IdValue);
Javascript Reference
<script language= "javascript"
src="<%=MyWebApp.App.Url%>/Common/Scripts/MyJavascriptFile.js" mce_src="<%=MyWebApp.App.Url%>/Common/Scripts/MyJavascriptFile.js"</script>
Recent Comments