2013-07-22 59 views
9

我的應用程序託管在不同的服務器上,我想要獲取當前服務器上的頁面URL。如何從ASP.NET代碼中獲取當前URL

如何在代碼後面獲得此屬性?

+0

的可能重複[獲取ASP.Net頁面代碼的網址-behind](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

另一種方式從代碼中獲取URL隱藏文件

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你會得到更多的信息。

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