Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net: Using System.Web.UI.Control.ResolveUrl() in a shared/static function

What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net? My current solution for VB.Net is:

Dim x As New System.Web.UI.Control x.ResolveUrl("~/someUrl") 

Or C#:

System.Web.UI.Control x = new System.Web.UI.Control(); x.ResolveUrl("~/someUrl"); 

But I realize that isn't the best way of calling it.

like image 878
travis Avatar asked Aug 25 '08 20:08

travis


2 Answers

I use System.Web.VirtualPathUtility.ToAbsolute.

like image 186
Dave Ward Avatar answered Sep 29 '22 23:09

Dave Ward


It's worth noting that although System.Web.VirtualPathUtility.ToAbsolute is very useful here, it is not a perfect replacement for Control.ResolveUrl.

There is at least one significant difference: Control.ResolveUrl handles Query Strings very nicely, but they cause VirtualPathUtility to throw an HttpException. This can be absolutely mystifying the first time it happens, especially if you're used to the way that Control.ResolveUrl works.

If you know the exact structure of the Query String you want to use, this is easy enough to work around, viz:

public static string GetUrl(int id) {     string path = VirtualPathUtility.ToAbsolute("~/SomePage.aspx");     return string.Format("{0}?id={1}", path, id); } 

...but if the Query String is getting passed in from an unknown source then you're going to need to parse it out somehow. (Before you get too deep into that, note that System.Uri might be able to do it for you).

like image 21
jdw Avatar answered Sep 29 '22 22:09

jdw