title: Get URL with virtual directory included?
body: <p>I am maintaining an ASP.NET Web Forms website <strong>(and I do mean website, it's not a web application)</strong>, and some of the static links are broken because they are hosting it with a virtual directory.</p>
  
  <pre><code>http://www.somewhere.com/MyApp
  </code></pre>
  
  <p>So, I started down the path to find a way to get an absolute URL given a virtual path to some page. And I found an article that mentioned you could take a link like this:</p>
  
  <pre><code>&lt;a href="/ContactUs.aspx"&gt;Contact Us&lt;/a&gt;
  </code></pre>
  
  <p>and do something like this:</p>
  
  <pre><code>&lt;a href="&lt;%= System.Web.VirtualPathUtility.ToAbsolute("/ContactUs.aspx") %&gt;"&gt;Contact Us&lt;/a&gt;
  </code></pre>
  
  <p>but that's not even working locally <strong>(i.e. against the ASP.NET Development Server)</strong> because my local path might be something like this:</p>
  
  <pre><code>http://localhost:7766/MyApp
  </code></pre>
  
  <p>but the path yielded by the <code>VirtualPathUtility</code> is this:</p>
  
  <pre><code>http://localhost:7766/ContactUs.aspx
  </code></pre>
  
  <hr>
  
  <p>So, I decided to deploy it to my local IIS instance and see how it would behave. And the outcome was the same. The local IIS path is:</p>
  
  <pre><code>http://localhost/MyApp
  </code></pre>
  
  <p>but the path to the contact us page is:</p>
  
  <pre><code>http://localhost/ContactUs.aspx
  </code></pre>
  
  <hr>
  
  <p>One final hitch in the get along, there is one link in the application that looks like this:</p>
  
  <pre><code>&lt;asp:HyperLink id="ContactUsLink"
      runat="server"
      Enabled="true"
      NavigateUrl="/ContactUs.aspx"
      Text="Contact Us"&gt;
  &lt;/asp:HyperLink&gt;
  </code></pre>
  
  <p>and the reason I say it's a hitch in the get along is because I know the inline code <strong>(like the examples above)</strong> don't work on server controls. It actually throws a compiler error:</p>
  
  <blockquote>
    <p>Server tags cannot contain &lt;% ... %> constructs.</p>
  </blockquote>
  
  <hr>
  
  <p>So it appears I'm clearly moving down the wrong path, and I need some help. I'm looking forward to your answers.</p>