Come verificare se una stringa è un URL HTTP valido?


Risposte:


452

Prova questo per convalidare gli URL HTTP ( uriNameè l'URI che vuoi testare):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && uriResult.Scheme == Uri.UriSchemeHttp;

Oppure, se si desidera accettare entrambi gli URL HTTP e HTTPS come validi (secondo il commento di J0e3gan):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

6
Dovrebbe leggere uriResult.Scheme invece di uriName.Scheme? Sto usando il sovraccarico di TryCreate che accetta String anziché Uri come primo parametro.

7
Potresti voler aggiungere più condizioni a uriResult.Scheme == ... Specificamente https. Dipende da ciò di cui hai bisogno, ma questo piccolo cambiamento era tutto ciò di cui avevo bisogno perché funzionasse perfettamente per me.
— Fiarr,

11
Per essere chiari per il commento di @ Fiarr, il "piccolo cambiamento" necessario per tenere conto di HTTPS oltre agli URL HTTP è:bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps;
— J0e3gan,

3
in questo modo non riesce per URL come abcde . Dice che questo è un URL valido.
— Kailash P,

7
Sembra che questa tecnica non superi
— Whitneyland,

98

Questo metodo funziona bene sia in http che in https. Solo una riga :)

if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute))

MSDN: IsWellFormedUriString


13
Ciò tornerà vero per gli URI non HTTP (ovvero qualsiasi altro schema come file://o ldap://. Questa soluzione dovrebbe essere accoppiata con un controllo rispetto allo schema - ad esempioif (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) ...
— Squiggle

Questo RFC3986 è conforme?
— Marcus,

3
@Squiggle È esattamente quello che voglio che controlli, tutto da quando sto realizzando un Downloader. Quindi, questa risposta è il metodo migliore per me.
— Beyondo,

24
    public static bool CheckURLValid(this string source)
    {
        Uri uriResult;
        return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
    }

Uso:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

AGGIORNAMENTO: (singola riga di codice) Grazie @GoClimbColorado

public static bool CheckURLValid(this string source) => Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps;

Uso:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

Questo non sembra gestire gli URL www. IE: www.google.com viene visualizzato come non valido.
— Zauber Paracelsus,

6
@ZauberParacelsus "www.google.com" non è valido. La media dell'URL dovrebbe iniziare con "http", "ftp", "file" ecc. La stringa dovrebbe essere "http: // www.google.com" senza spazio
— Erçin Dedeoğlu,

1
Oggi, il parametro out può apportare un miglioramentoUri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps
— GoClimbColorado,

11

Tutte le risposte qui consentono gli URL con altri schemi (ad es. file://, ftp://) O rifiutano gli URL leggibili dall'uomo che non iniziano con http://o https://(ad es. www.google.com) , Il che non va bene quando si tratta degli input dell'utente .

Ecco come lo faccio:

public static bool ValidHttpURL(string s, out Uri resultURI)
{
    if (!Regex.IsMatch(s, @"^https?:\/\/", RegexOptions.IgnoreCase))
        s = "http://" + s;

    if (Uri.TryCreate(s, UriKind.Absolute, out resultURI))
        return (resultURI.Scheme == Uri.UriSchemeHttp || 
                resultURI.Scheme == Uri.UriSchemeHttps);

    return false;
}

Uso:

string[] inputs = new[] {
                          "https://www.google.com",
                          "http://www.google.com",
                          "www.google.com",
                          "google.com",
                          "javascript:alert('Hack me!')"
                        };
foreach (string s in inputs)
{
    Uri uriResult;
    bool result = ValidHttpURL(s, out uriResult);
    Console.WriteLine(result + "\t" + uriResult?.AbsoluteUri);
}

Produzione:

True    https://www.google.com/
True    http://www.google.com/
True    http://www.google.com/
True    http://google.com/
False

1
Questo lascia passare parole singole come "mooooooooo" ma usato insieme a Uri.IsWellFormedUriString potrebbe essere buono
— Epirocks

@Epirocks Questo è un buon punto. Il problema è che http://mooooooooo, in effetti, è un Uri valido. Pertanto, non è possibile verificare Uri.IsWellFormedUriStringdopo aver inserito "http: //" e se lo si verifica prima, tutto ciò che non ha un Schemeverrà rifiutato. Forse quello che si può fare è controllare s.Contains('.')invece.
— Ahmed Abdelhameed

moooooo da solo non sembra un url in quanto non ha protocollo. Quello che ho fatto è stato eliminare il tuo call match regex, e lo ha fatto anche con IsWellFormedUriString.
— Epirocks,

@Epirocks esattamente! Il problema è che se lo usi IsWellFormedUriStringprima di aggiungere http://, finirai per rifiutare cose del genere google.come se lo usi dopo aver aggiunto il http://, tornerà comunque vero per http://mooooooooo. Ecco perché ho suggerito di verificare se la stringa contiene .invece un .
— Ahmed Abdelhameed

va bene per me comunque non voglio accettare un URL senza http o https su di esso. Quindi uso prima IsWellFormedUriString, quindi uso la tua funzione senza regex. bool bResult = (Uri.IsWellFormedUriString (s, UriKind.Absolute) && ValidHttpURL (s, out uriResult)); Grazie
— Epirocks,


3

Prova questo:

bool IsValidURL(string URL)
{
    string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
    Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    return Rgx.IsMatch(URL);
}

Accetterà URL in questo modo:

  • http (s): //www.example.com
  • http (s): //stackoverflow.example.com
  • http (s): //www.example.com/page
  • http (s):? //www.example.com/page id = 1 & product = 2
  • http (s): //www.example.com/page#start
  • http (s): //www.example.com: 8080
  • http (s): //127.0.0.1
  • 127.0.0.1
  • www.example.com
  • example.com

2

Ciò restituirebbe bool:

Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)

2
Penso che l'OP menzionato specificamente, non gli piaccia Uri.IsWellFormedUriString in quanto dà vero per i percorsi dei file. Hai una soluzione per questo problema?
— Isantipov,

1
Uri uri = null;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri)
    return false;
else
    return true;

Ecco urlla stringa che devi testare.


3
null == il controllo dell'URL è orribilmente ridondante
— JSON

0
bool passed = Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)

La tua risposta è arrivata in post di qualità inferiore. Fornisci alcune spiegazioni anche se il tuo codice è autoesplicativo.
— Harsha Biyani,
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.