Click here to Skip to main content
Click here to Skip to main content

ResolveUrl in ASP.NET - The Perfect Solution

By , 26 Jan 2010
 

Introduction/Background

From my personal experience using ASP.NET, and from searching the web, I have found that the ResolveUrl method of the Page control (and basically, Control) presents us with some serious problems.

The most common one is that you just cannot use it outside of the page or control context.

Other problems are just bugs. It will not correctly handle some of the URLs you'll give it. For example, try Page.ResolveUrl("~/test.aspx?param=http://www.test.com"). The result is the very same input string... It will just do nothing. By looking into the ASP.NET code using Reflector, I found that all mechanisms that are supposed to convert the relative URLs to absolute URLs will search first for a "://" inside the string, and will return if found. So a query string is OK, unless you pass in a parameter with ://. Yes, I know that the query string parameter should be UrlEncoded, but if it isn't, it is still an acceptable URL. Seriously, check your browsers!

Other suggested methods on the web involve using VirtualPathUtility.ToAbsolute, which is pretty nice and handy, unless you pass in a query string with the URL... Because it will just throw an exception. It will also throw an exception for an absolute URL!

So I decided to find the ultimate solution.

Using the Code

First, I searched for the perfect variable that will give me the Application Virtual Path at runtime without a page context.

I found this to be HttpRuntime.AppDomainAppVirtualPath. It will work anywhere - even inside a timer callback! It gives the path without a trailing slash (ASP.NET makes a special effort to remove the trailing slash...), but that is OK, we can fix it :-)

Then, I did some tests on the original ResolveUrl code, and found where I need to replace what with the AppVirtualPath:

  1. When the URL begins with a slash (either / or \), it will not touch it!
  2. When the URL begins with ~/, it will replace it with the AppVirtualPath.
  3. When the URL is an absolute URL, it will not touch it. (ResolveUrl has a bug with this, as I said before...)
  4. In any other case (even beginning with ~, but not slash), it will append the URL to the AppVirtualPath.
  5. Whenever it modifies the URL, it also fixes up the slashes. Removes double slashes and replaces \ with /.

So I replicated all of that, but without the bugs. And here's the code:

public static string ResolveUrl(string relativeUrl)
{
    if (relativeUrl == null) throw new ArgumentNullException("relativeUrl");
 
    if (relativeUrl.Length == 0 || relativeUrl[0] == '/' || relativeUrl[0] == '\\') 
        return relativeUrl;
 
    int idxOfScheme = relativeUrl.IndexOf(@"://", StringComparison.Ordinal);
    if (idxOfScheme != -1)
    {
        int idxOfQM = relativeUrl.IndexOf('?');
        if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl;
    }
 
    StringBuilder sbUrl = new StringBuilder();
    sbUrl.Append(HttpRuntime.AppDomainAppVirtualPath);
    if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/');
 
    // found question mark already? query string, do not touch!
    bool foundQM = false;
    bool foundSlash; // the latest char was a slash?
    if (relativeUrl.Length > 1
        && relativeUrl[0] == '~'
        && (relativeUrl[1] == '/' || relativeUrl[1] == '\\'))
    {
        relativeUrl = relativeUrl.Substring(2);
        foundSlash = true;
    }
    else foundSlash = false;
    foreach (char c in relativeUrl)
    {
        if (!foundQM)
        {
            if (c == '?') foundQM = true;
            else
            {
                if (c == '/' || c == '\\')
                {
                    if (foundSlash) continue;
                    else
                    {
                        sbUrl.Append('/');
                        foundSlash = true;
                        continue;
                    }
                }
                else if (foundSlash) foundSlash = false;
            }
        }
        sbUrl.Append(c);
    }
 
    return sbUrl.ToString();
}

Points of Interest

After completing the code and testing over and over again and comparing to the original ResolveUrl, I started to test for performance... In most cases, my code executed faster than the original ResolveUrl by 2.7 times! I also tested inside loops that executed the code 100000s of times on different kinds of URLs.

History

This is the first version, and hopefully the last!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Daniel Cohen Gindi
Software Developer (Senior)
Israel Israel
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionSystem.Web.VirtualPathUtility?membermwdiablo11 Oct '12 - 15:51 
Why would you not use System.Web.VirtualPathUtility?
AnswerRe: System.Web.VirtualPathUtility?memberDaniel Cohen Gindi11 Oct '12 - 20:31 
System.Web.VirtualPathUtility is for Paths, not Urls.
-----
Daniel Cohen Gindi
danielgindi (at) gmail dot com

GeneralJust what I came here for...memberSixOfTheClock4 Aug '12 - 10:56 
I was looking for a solution to my ResolveUrl problem and here it is, taking me all of 5 minutes to implement. Excellent article! And here's a 5!
A programming language is to a programmer what a fine hat is to one who is fond of fancy garden parties. Just don't try wearing any .NET language on your head. Some of them are sharp.

GeneralRe: Just what I came here for...memberDaniel Cohen Gindi4 Aug '12 - 10:57 
Glad I could help! Smile | :)
-----
Daniel Cohen Gindi
danielgindi (at) gmail dot com

SuggestionA suggestion to make it even bettermemberRobbie Couret9 Nov '11 - 9:55 
It does not work like Page.ResolveUrl would when the current page is in a subdirectory and you do not supply the subdirectory name in the call, for instance: lets assume we are currently on http://root/sub/page1.aspx and we then call:
string url = Page.ResolveUrl("page2.aspx");
then the url output would be "/sub/page2.aspx", however:
string url = WebUtil.ResolveUrl("page2.aspx"); // WebUtil being a static class containing this article's method
would yield "/page2.aspx" which is understandable since it can not make the subdirectory determination from the string parameter alone.
 
One could argue that the developer should remember to include the subdirectory in the relativeUrl parameter when making the call, but I think for increased backwards compatibility with Page.ResolveUrl and peace of mind, that the method should at least try to figure out what the current subdirectory is in these cases when HttpContext.Current (and HttpContext.Current.Request) is available.
Robbie Couret
Senior Software Engineer
Big Easy Software, LLC

GeneralMy vote of 5memberAnurag Gandhi4 Aug '11 - 20:46 
Nice approach. Well done.
GeneralGreat job!memberDotNetWise8 Dec '10 - 12:23 
Dude, you rocked my day! Laugh | :laugh:
GeneralMy vote of 5memberToeStumper1 Sep '10 - 6:02 
Great tool to handle a specific set of issues. I'll ding you for the title "Perfect...?" but the article and code were great!
GeneralRe: My vote of 5memberDaniel Cohen Gindi1 Sep '10 - 10:02 
Thanks! Always happy to help!
 
What do you know maybe Microsoft will adopt my code in the next .Net version Wink | ;-)
-----
Daniel Cohen Gindi
danielgindi (at) gmail dot com

GeneralGreat job!memberToeStumper1 Sep '10 - 5:59 
I stumbled on to this when I was changing a Response.Redirect to Server.Transfer call. There was no need for my code to take a trip to the browser to get to the page I wanted so I went from this
 
string req = ResolveUrl("~/MyPage.aspx");
Response.Redirect(req);
 
to this
 
string req = ResolveUrl("~/MyPage.aspx");
Server.Transfer(req);
 
and found out it didn't work too well (Boom!). You gave a great explanation of the situation and provided a well done tool to address some concerns.
 
Thank you.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 26 Jan 2010
Article Copyright 2010 by Daniel Cohen Gindi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid