I am maintaining an ASP.NET Web Forms website (and I do mean website, it's not a web application), and some of the static links are broken because they are hosting it with a virtual directory.
http://www.somewhere.com/MyApp
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:
<a href="/ContactUs.aspx">Contact Us</a>
and do something like this:
<a href="<%= System.Web.VirtualPathUtility.ToAbsolute("/ContactUs.aspx") %>">Contact Us</a>
but that's not even working locally (i.e. against the ASP.NET Development Server) because my local path might be something like this:
http://localhost:7766/MyApp
but the path yielded by the VirtualPathUtility
is this:
http://localhost:7766/ContactUs.aspx
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:
http://localhost/MyApp
but the path to the contact us page is:
http://localhost/ContactUs.aspx
One final hitch in the get along, there is one link in the application that looks like this:
<asp:HyperLink id="ContactUsLink"
runat="server"
Enabled="true"
NavigateUrl="/ContactUs.aspx"
Text="Contact Us">
</asp:HyperLink>
and the reason I say it's a hitch in the get along is because I know the inline code (like the examples above) don't work on server controls. It actually throws a compiler error:
Server tags cannot contain <% ... %> constructs.
So it appears I'm clearly moving down the wrong path, and I need some help. I'm looking forward to your answers.
Try:
Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath
You should prefix your addresses with a ~. so "~/Contact.aspx" on any runat=server control. This won't work for a standard tag. You can add runat=server to a normal tag to make it a server control.
The runtime will see the ~ and make it relative to what you're running as.
<asp:HyperLink id="ContactUsLink"
runat="server"
Enabled="true"
NavigateUrl="~/ContactUs.aspx"
Text="Contact Us">
</asp:HyperLink>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With