12

My application is hosted on different servers, and I want to get the URL of the page on the current server.

How can you get this property in code behind?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
  • possible duplicate of [Get URL of ASP.Net Page in code-behind](http://stackoverflow.com/questions/96029/get-url-of-asp-net-page-in-code-behind) – Dan Drews Jul 22 '13 at 13:22

5 Answers5

31
string url = HttpContext.Current.Request.Url.AbsoluteUri;

http://thehost.com/dir/Default.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;

/dir/Default.aspx

string host = HttpContext.Current.Request.Url.Host;

thehost.com

YaakovHatam
  • 2,314
  • 2
  • 22
  • 40
  • 1
    What if i have '#' in URL..... i.e :http:test.abc.com/sitesposure.aspx#commentfocus......... will it work? – Pranav Bilurkar Jan 27 '15 at 14:57
  • 2
    @Pranav-BitWiser HttpContext.Current.Request.Url returns a System.Uri. Here's a summary of all of the Uri properties: http://blog.jonschneider.com/2014/10/systemuri-net-framework-45-visual-guide.html – Jon Schneider Jan 19 '16 at 18:54
9

Another way to get URL from code behind file

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

        //Getting the current context of HTTP request
        var 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;
    }
}

check this Link you will get more info.

IMMORTAL
  • 2,707
  • 3
  • 21
  • 37
5
string MyUrl = HttpContext.Current.Request.Url.AbsoluteUri
sm_
  • 2,572
  • 2
  • 17
  • 34
5

string path = HttpContext.Current.Request.Url.AbsolutePath;

Prasad
  • 220
  • 3
  • 9
1
public string GetApplicationName(){
    string url = HttpContext.Current.Request.Url.AbsoluteUri;
    int intStartIndex = GetIndex(url, 3);
    int intEndIndex = GetIndex(url, 4);
    return url.Substring(intStartIndex, (intEndIndex - intStartIndex) - 1);
}

public int GetIndex(string str, int indexNo){
    int index = 0;
    for (int i = 0; i < indexNo; i++){
        int tempIndex = str.IndexOf("/") + 1;
        str = str.Remove(0, tempIndex);
        index += tempIndex;
    }
    return index;
}
Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66