Get Absolute URL of ASP.Net Application

In one of my web projects, I needed to pass the name of a specific URL inside the application to another application. So the first task was: how do I find the absolute URL of an ASP.Net application’s root directory.

I tried ResolveClientUrl, which, according to MSDN, returns

A fully qualified URL to the specified resource suitable for use on the browser

As I was expecting an absolute URL from this description, it turned out, it doesn’t. (There also seems to be a terminological confusion between a Fully Qualified Domain Name, and Absolute and Relative URLs)

Both ResolveUrl and ResolveClientUrl create URLs relative to the page’s URL or the application root, but no absolute URL.

Fortunately, I found this entry on geekpedia, which provided a solution (that I was very close to develop on my own ;) )

public string FullyQualifiedApplicationPath
{
  get
  {
    //Return variable declaration
    string appPath = null;

    //Getting the current context of HTTP request
    HttpContext context = HttpContext.Current;

    //Checking the current context content
    if (context != null)
    {
      //Formatting the fully qualified website url/name
      appPath = string.Format("{0}://{1}{2}{3}",
        context.Request.Url.Scheme,
        context.Request.Url.Host,
        context.Request.Url.Port == 80
          ? string.Empty : ":" + context.Request.Url.Port,
        context.Request.ApplicationPath);
    }
    if (!appPath.EndsWith("/"))
      appPath += "/";
    return appPath;
  }
}

Of course, if you are inside a Page’s context, this reduced version is sufficient

string appPath = string.Format("{0}://{1}{2}{3}",
  context.Request.Url.Scheme,
  context.Request.Url.Host,
  context.Request.Url.Port == 80
    ? string.Empty : ":" + context.Request.Url.Port,
  context.Request.ApplicationPath);
if (!appPath.EndsWith("/"))
  appPath += "/";
About these ads

2 Responses to Get Absolute URL of ASP.Net Application

  1. Ahmad says:

    I love you :)

  2. gburek says:

    Thank you for the example.

    Just one note: there is no point checking context against null as you’ll get NPE in the next if

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 72 other followers

%d bloggers like this: