Existen los métodos Uri.IsWellFormedUriStringy Uri.TryCreate, pero parecen volver truepara rutas de archivos, etc.
¿Cómo verifico si una cadena es una URL HTTP válida (no necesariamente activa) para fines de validación de entrada?
Existen los métodos Uri.IsWellFormedUriStringy Uri.TryCreate, pero parecen volver truepara rutas de archivos, etc.
¿Cómo verifico si una cadena es una URL HTTP válida (no necesariamente activa) para fines de validación de entrada?
Respuestas:
Pruebe esto para validar las URL HTTP ( uriNamees el URI que desea probar):
Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)
&& uriResult.Scheme == Uri.UriSchemeHttp;
O, si desea aceptar las URL HTTP y HTTPS como válidas (según el comentario de J0e3gan):
Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps;
Este método funciona bien tanto en http como en https. Solo una línea :)
if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute))
MSDN: IsWellFormedUriString
file://o ldap://. Esta solución debe combinarse con una verificación contra el esquema, por ejemploif (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) ...
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
}
ACTUALIZACIÓN: (línea única de código) Gracias @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
}
Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps
Todas las respuestas aquí permiten URL con otros esquemas (p. Ej. file://, ftp://) O rechazan las URL legibles por humanos que no comienzan con http://o https://(p. Ej. www.google.com) , Lo que no es bueno cuando se trata de entradas de usuario .
Así es como lo hago:
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);
}
Salida:
True https://www.google.com/
True http://www.google.com/
True http://www.google.com/
True http://google.com/
False
http://mooooooooo, de hecho, es un Uri válido. Por lo tanto, no puede verificarlo Uri.IsWellFormedUriStringdespués de insertar "http: //" y si lo verifica antes, cualquier cosa que no tenga un Schemeserá rechazado. Tal vez lo que se puede hacer es verificar en su s.Contains('.')lugar.
IsWellFormedUriStringantes de agregar el http://, terminará rechazando cosas como, google.comy si lo usa después de agregar el http://, seguirá siendo cierto para http://mooooooooo. Es por eso que sugerí verificar si la cadena contiene un .en su lugar.
Después de Uri.TryCreateque puede verificar Uri.Schemesi HTTP (s).
Trata eso:
bool IsValidURL(string URL)
{
string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return Rgx.IsMatch(URL);
}
Aceptará URL así:
Esto devolvería bool:
Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)
bool passed = Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)