Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine site's absolute, fully-qualified url in asp.net

Tags:

url

uri

asp.net

How can I consistently get the absolute, fully-qualified root or base url of the site regardless of whether the site is in a virtual directory and regardless of where my code is in the directory structure? I've tried every variable and function I can think of and haven't found a good way.

I want to be able to get the url of the current site, i.e. http://www.example.com or if it's a virtual directory, http://www.example.com/DNN/


Here's some of the things I've tried and the result. The only one that includes the whole piece that I want (http://localhost:4471/DNN441) is Request.URI.AbsoluteURI:

  • Request.PhysicalPath: C:\WebSites\DNN441\Default.aspx
  • Request.ApplicationPath: /DNN441
  • Request.PhysicalApplicationPath: C:\WebSites\DNN441\
  • MapPath: C:\WebSites\DNN441\DesktopModules\Articles\Templates\Default.aspx
  • RawURL: /DNN441/ModuleTesting/Articles/tabid/56/ctl/Details/mid/374/ItemID/1/Default.aspx
  • Request.Url.AbsoluteUri: http://localhost:4471/DNN441/Default.aspx
  • Request.Url.AbsolutePath: /DNN441/Default.aspx
  • Request.Url.LocalPath: /DNN441/Default.aspx Request.Url.Host: localhost
  • Request.Url.PathAndQuery: /DNN441/Default.aspx?TabId=56&ctl=Details&mid=374&ItemID=1
like image 670
EfficionDave Avatar asked Sep 23 '08 16:09

EfficionDave


2 Answers

In reading through the answer provided in Rick Strahl's Blog I found what I really needed was quite simple. First you need to determine the relative path (which for me was the easy part), and pass that into the function defined below:

VB.NET

Public Shared Function GetFullyQualifiedURL(ByVal s as string) As String
   Dim Result as URI = New URI(HttpContext.Current.Request.Url, s)
   Return Result.ToString
End Function

C#

public static string GetFullyQualifiedURL(string s) {
    Uri Result = new Uri(HttpContext.Current.Request.Url, s);
    return Result.ToString();
}
like image 59
3 revs Avatar answered Oct 03 '22 04:10

3 revs


The accepted answer assumes that the current request is already at the server/virtual root. Try this:

Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath
like image 42
Scott Stafford Avatar answered Oct 03 '22 04:10

Scott Stafford