Friday, April 27, 2007

Getting a fully qualified url for a page

You have an ASP.NET application. Your application creates an email let's say. In the email you want to show a link back to a page in your application. Believe it or not, there is not a pre-packaged method in ASP.NET that does this. Here is the solution. /// <summary> /// Changes a relative path such as /MyPage.aspx or ~/MyPage.aspx to /// a fully qualified path such as http://myhost/myAppPath/MyPage.aspx /// </summary> /// <param name="pagePath">relative path page need fully qualified path for</param> /// <returns>fully qualified path</returns> public string GetFullyQualifiedPath(string pagePath) { string absUrl = string.Empty; HttpRequest request = HttpContext.Current.Request; Uri url = request.Url; string host = url.DnsSafeHost; string appPath = request.ApplicationPath; absUrl = string.Format("http://{0}{1}{2}", host, appPath, pagePath).Replace("~", ""); return absUrl; } Here is another way to do it also. Same idea. public static string GetFullyQualifiedUrl(string relativeUrl) { string host = HttpContext.Current.Request.Url.Host; int port = HttpContext.Current.Request.Url.Port; UriBuilder uriBuilder = new UriBuilder("http", host, port, relativeUrl); string fullyQualifiedUrl = uriBuilder.Uri.AbsolutePath; return fullyQualifiedUrl; }

If you just want to know the url of the page that is requested, here is the simplest way to do this.

string url = HttpContext.Current.Request.Url.ToString();

For more information on paths, check out this blog: http://west-wind.com/weblog/posts/269.aspx

1 comment:

digital signature sharepoint said...

I am a newbie in ASP.Net and was searching for how to get a fully qualified url for a page.Thanks for sharing the informative blog here.