Come posso ottenere l'URI del dominio principale in ASP.NET?


96

Diciamo che sto ospitando un sito web su http://www.foobar.com .

C'è un modo in cui posso accertare programmaticamente " http://www.foobar.com/ " nel mio codice sottostante (cioè senza doverlo codificare nella mia configurazione web)?


7
Poiché dipende dalla richiesta, potresti provare a guardare Requestnell'oggetto.
John Saunders

Risposte:


79

HttpContext.Current.Request.Url può ottenere tutte le informazioni sull'URL. E può scomporre l'URL nei suoi frammenti.


4
Sì, perché il voto negativo? Non vedere qualcosa contrassegnato come risposta e spesso sottovalutato. : /
Zack

4
Anche a me non piace questa risposta. blesh ha dato quello giusto e questo avrebbe dovuto essere contrassegnato come risposta ...
Michal B.

-1 - Request.Url fornisce spesso un URL come "/ cartella1 / cartella2" ed esclude del tutto il dominio.
Justin

4
@Justin: Request.Url ti dà un oggetto Uri che ha tutti i pezzi suddivisi per te. Non dovrebbe darti una stringa. Almeno non nella versione di .net che sto usando
JoshBerke

6
Questa risposta potrebbe essere migliorata aggiungendo il codice che la fa funzionare come la risposta sotto che ha più voti su ...
theJerm

171
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);

Metodo Uri :: GetLeftPart :

Il metodo GetLeftPart restituisce una stringa contenente la parte più a sinistra della stringa URI, che termina con la parte specificata da part.

Enumerazione UriPartial :

Lo schema e i segmenti di autorità dell'URI.


5
Molto meglio quindi analizzare Url!
Evgenyt

1
questa è la risposta migliore! tnx!
AminM

Questa dovrebbe essere la risposta selezionata. Troppe manipolazioni di stringhe non necessarie.
Ghasan

1
Utilizzando questo metodo, http: // www.lala.xxx/blah/blah restituirà http: // www.lala.xxx
live-love

+1 E non è la stessa di .Authority che - nei test che ho fatto su localhost - tralascia la parte del protocollo (http: //).
GGleGrand

122

Per chiunque ancora si chieda, una risposta più completa è disponibile su http://devio.wordpress.com/2009/10/19/get-absolut-url-of-asp-net-application/ .

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

4
Ha funzionato perfettamente. Se il sito è server: 8080 / MySiteName , lo ottiene correttamente.
Michael La Voie

2
Grazie per aver condiviso il codice effettivo invece di un collegamento da qualche altra parte.
theJerm

2
context.Request.Url.Port == 80 causerà problemi all'interno di HTTPS
Evgenyt

7
Attenzione! Non funziona per https. Per https necessario sostituire context.Request.Url.Port == 80 da (context.Request.Url.Port == 80 && context.Request.Url.Scheme == "http") || (context.Request.Url.Port == 443 && context.Request.Url.Scheme == "https")o l'uso risposta qui sotto
Razon

1
Funziona anche per localhost (se stai testando localmente). Se non hai bisogno della porta, puoi usare "http: //" + HttpContext.Current.Request.Url.Host;
CyberHawk

32

Se l'URL di esempio è http://www.foobar.com/Page1

HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"


HttpContext.Current.Request.Url.Host; //returns "www.foobar.com"


HttpContext.Current.Request.Url.Scheme; //returns "http/https"


HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"

1
No, no. .Hostdi "http://www.foobar.com/Page1"è www.foobar.com, non foobar.com.
tchelidze

1
si hai ragione, aggiornata la risposta. @tchelidze thanks
Dheeraj Palagiri

27
string hostUrl = Request.Url.Scheme + "://" + Request.Url.Host; //should be "http://hostnamehere.com"

16

Per ottenere l'intera stringa dell'URL della richiesta:

HttpContext.Current.Request.Url

Per ottenere la parte www.foo.com della richiesta:

HttpContext.Current.Request.Url.Host

Nota che sei, in una certa misura, alla mercé di fattori esterni alla tua applicazione ASP.NET. Se IIS è configurato per accettare più o qualsiasi intestazione host per la tua applicazione, uno qualsiasi di quei domini che sono stati risolti nell'applicazione tramite DNS potrebbe essere visualizzato come URL di richiesta, a seconda di quello inserito dall'utente.


1
soluzione più semplice qui
full_prog_full

4
Match match = Regex.Match(host, "([^.]+\\.[^.]{1,3}(\\.[^.]{1,3})?)$");
string domain = match.Groups[1].Success ? match.Groups[1].Value : null;

host.com => restituisci host.com
s.host.com => restituisci host.com

host.co.uk => restituisci host.co.uk www.host.co.uk
=> restituisci host.co.uk
s1.www.host.co.uk => restituisci host.co.uk


Mi rendo conto che questo è un vecchio post, ma NQuenault ben fatto, non sono bravo con Regex Expressions così ben fatto. Esattamente quello di cui avevo bisogno.
JeffreyJ

@nquenault qualche idea su come gestire al meglio un nome host come www.abc.com? Grazie!
Gary Ewan Park

4

- L'aggiunta della porta può aiutare durante l'esecuzione di IIS Express

Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port

3
string domainName = Request.Url.Host

3

So che è più vecchio ma il modo corretto per farlo ora è

string Domain = HttpContext.Current.Request.Url.Authority

Ciò otterrà il DNS o l'indirizzo IP con la porta per un server.



1

Esempio di C # di seguito:

string scheme = "http://";
string rootUrl = default(string);
if (Request.ServerVariables["HTTPS"].ToString().ToLower() == "on")
{
  scheme = "https://";
}
rootUrl = scheme + Request.ServerVariables["SERVER_NAME"].ToString();

1
string host = Request.Url.Host;
Regex domainReg = new Regex("([^.]+\\.[^.]+)$");
HttpCookie cookie = new HttpCookie(cookieName, "true");
if (domainReg.IsMatch(host))
{
  cookieDomain = domainReg.Match(host).Groups[1].Value;                                
}

1

Questo restituirà specificamente ciò che stai chiedendo.

Dim mySiteUrl = Request.Url.Host.ToString()

So che questa è una vecchia domanda. Ma avevo bisogno della stessa semplice risposta e questa restituisce esattamente ciò che viene richiesto (senza http: //).

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.