2013-07-22 21 views
9

Meine Anwendung wird auf verschiedenen Servern gehostet, und ich möchte die URL der Seite auf dem aktuellen Server abrufen.So erhalten Sie die aktuelle URL von ASP.NET-Code hinter

Wie können Sie diese Eigenschaft in Code erhalten?

+0

möglich Duplikat von [URL erhalten von ASP.Net Seite in Code -behind] (http://stackoverflow.com/questions/96029/get-u.) rl-of-asp-net-seite-in-code-behind) –

Antwort

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

Was passiert, wenn ich '#' in der URL habe ..... d. H .: http: test.abc.com/sitesposure.aspx#commentfocus ......... wird es funktionieren? –

+1

@ Pranav-BitWiser HttpContext.Current.Request.Url gibt eine System.Uri zurück. Hier ist eine Zusammenfassung aller Uri-Eigenschaften: http://blog.jonschneider.com/2014/10/systemuri-net-framework-45-visual-guide.html –

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

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

+0

das gab mir /dir/Default.aspx. @Siraj Lösung gab mir http: // localhost: 1872/dir/Default.aspx und das ist, was ich brauche. Vielen Dank. – dotnetandsqldevelop

5

Eine andere Möglichkeit, URL von Code hinter Datei

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

Kontrolle dieses Link Sie erhalten weitere Informationen zu erhalten.

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