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:


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.

    <add key="ApplicationPath" value="http://localhost:5521/XYZ/" />
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
        //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.Port == 80
                ? string.Empty : ":" + context.Request.Url.Port,
        if (!applicationPath.EndsWith("/"))
            applicationPath += "/";
        return applicationPath;

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

(Visited 174 times, 1 visits today)