Monday, December 7, 2009

Anti-Sample Of The Day - Request.ApplicationPath +"/mypath"

Imagine the following 3 alternatives of setting link URI:

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/foobar.txt" Text="asp:HyperLink ~foobar.txt"/><br/>
<asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="" Text="HyperLink2.NavigateUrl = Request.ApplicationPath + '/foobar.txt';"/><br/>
<a href="<%=Request.ApplicationPath+"/foobar.txt"%>">Request.ApplicationPath+"/foobar.txt"</a>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
HyperLink2.NavigateUrl = Request.ApplicationPath + "/foobar.txt";
}
</script>


Run under /sample application (seems fine):
href=
1."../../../../foobar.txt"
2."/sample/foobar.txt"
3."/sample/foobar.txt"

Run under / (breaks links 2,3):
1."foobar.txt"
2."//foobar.txt"
3."//foobar.txt"



Source: MSDN, search for ApplicationPath samples. Or one is located directly under ApplicationPath docs:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.applicationpath.aspx
with small excuse in Remarks section
Use this property to construct a URL relative to the application root from a page or Web user control that is not in the root directory.
BTW: In "equivalent Servlet API" getContextPath()" they have made decision elminating this sort of concat mistake:
The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "".

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

    ReplyDelete