25

Is there any benifit to using one of these methods over the other when resolving paths which start with the tilde (~)?

Generally, what is a better practice, should you be sending relative paths or absolute paths down in your html?

Aaron Hoffman
  • 6,604
  • 8
  • 56
  • 61
Bob
  • 97,670
  • 29
  • 122
  • 130

4 Answers4

26

The difference between ResolveUrl and ResolveClientUrl is that ResolveClientUrl returns a path relative to the current page, ResolveUrl returns a path relative to the site root:

http://www.andornot.com/blog/post/ResolveUrl-vs-ResolveClientUrl.aspx

I would recommend using absolute paths.

Edit: Rick Strahl posted a nice article about this

Edit2: Removed bit about caching. Does not add to the answer and may not necessarily be accurate.

http://west-wind.com/weblog/posts/132081.aspx

Pent Ploompuu
  • 5,364
  • 1
  • 27
  • 47
Aaron Hoffman
  • 6,604
  • 8
  • 56
  • 61
  • +1 good one. BTW, how may it help with caching? (And which caching?) – mtmk Jan 20 '10 at 17:33
  • At the time I was thinking it may help the client (or browser) cache images and such from the server (that is if the caching service was not very intelligent, it may duplicate items if relative paths are used). But I can't say for certain, so I removed that. – Aaron Hoffman Jan 20 '10 at 18:40
  • 1
    If you're stuck with a legacy app using cookieless session where the session Id is in the URI then VirtualPathUtility.ToAbsolute will exclude the sessionId from the URL, i.e. better caching of CSS, JPG, and External Javascript files. Because if SessionID is in the URL the browser will get the resource at least once for every new session instead of from Browser's Private Cache. – Charles Byrne Jun 23 '14 at 17:03
5

Here's another article that explains the difference between the various ways to resolving paths in ASP.NET -

Different approaches for resolving URLs in ASP.NET

Rohit Agarwal
  • 4,269
  • 3
  • 27
  • 22
4

Note that VirtualPathUtility.ToAbsolute(virtualPath) will throw an exception if a query string is included in the path.

The HttpException message will be along the lines of "'~/YourVirtualPath/YourPage.aspx?YourQueryStringArg=FooBar' is not a valid virtual path."

See Rick Strahl's Web Log:ResolveUrl() without Page and MSDN: VirtualPathUtility.ToAbsolute Method (String)

Daniel Ballinger
  • 13,187
  • 11
  • 69
  • 96
1

Another difference I noticed:

Code:

string value = "~/Docs/Hello & World.aspx"; Response.Write(HyperLink1.ResolveClientUrl(value) + "<br/>"); Response.Write(HyperLink1.ResolveUrl(value) + "<br/>");

Result:

Docs/Hello%20&%20World.aspx

/Docs/Hello & World.aspx

ravi
  • 949
  • 11
  • 22