Get Absolute URL – Web Application

Getting fully qualified absolute path of ASP.NET application is always tricky and problem arises when code moves across various platform. Hard coding the Application Path is no where a good solution here.

The URL syntax is:

scheme://domain:port/path?query_string#fragment_id

Two solutions that you can look for in such scenarios:

1. Add an entry in your web.config file and use it across your application.

<configuration>
  <appSettings>
    <add key="ApplicationPath" value="http://localhost:5521/XYZ/" />
  </appSettings>
</configuration>
string myPath = ConfigurationManager.AppSettings["ApplicationPath"] + "default.aspx";

So, you need to change this entry at various platforms as code moves along.
2. Programmatically, construct you application path from HTTP Request object.

public string FullyQualifiedApplicationPath
{
    get
    {
        //Return variable declaration
        string applicationPath = string.Empty;

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

        //Checking the current context content
        if (context != null)
        {
            //Formatting the fully qualified website url/name
            applicationPath = 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 (!applicationPath.EndsWith("/"))
            applicationPath += "/";
        return applicationPath;
    }
}

This code will automatically picks up appropriate path and no intervention is needed.

(Visited 333 times, 1 visits today)