2013-07-22 4 views
9

내 응용 프로그램이 다른 서버에서 호스팅되며 현재 서버에서 페이지의 URL을 가져 오려고합니다.ASP.NET 코드에서 현재 URL을 가져 오는 방법

어떻게 코드에서이 속성을 얻을 수 있습니까?

+0

가능한 중복 [가져 오기 코드에서 ASP.Net 페이지의 URL - 뒤에서] (http://stackoverflow.com/questions/96029/get-u rl-of-asp-net-page-in-code-behind) –

답변

24
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의

+1

URL에 '#'이 있으면 어떻게됩니까? 예 : http : test.abc.com/sitesposure.aspx#commentfocus ......... 작동합니까? –

+1

@ Pranav-BitWiser HttpContext.Current.Request.Url은 System.Uri를 반환합니다. 다음은 Uri 속성에 대한 요약입니다. http://blog.jonschneider.com/2014/10/systemuri-net-framework-45-visual-guide.html –

5
string MyUrl = HttpContext.Current.Request.Url.AbsoluteUri 
5

문자열 경로 = HttpContext.Current.Request.Url.AbsolutePath;

+0

이것은 나에게 /dir/Default.aspx를 주었다. @Siraj 솔루션은 http : // localhost : 1872/dir/Default.aspx를주었습니다. 감사. – dotnetandsqldevelop

5

또 다른 방법은 당신이 더 많은 정보를 얻을 것이다 파일 뒤에 코드에서

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; 
    } 
} 

확인이 Link를 URL을 얻을 수 있습니다.

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; 
} 
관련 문제