有Uri.IsWellFormedUriString
和Uri.TryCreate
方法,但它们似乎返回true
文件路径等。
如何检查字符串是否是用于输入验证的有效(不一定是活动的)HTTP URL?
尝试此验证HTTP URL(uriName
是您要测试的URI):
Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)
&& uriResult.Scheme == Uri.UriSchemeHttp;
或者,如果您要同时接受HTTP和HTTPS URL(根据J0e3gan的评论):
Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
此方法在http和https中均可正常工作。只需一行:)
if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute))
public static bool CheckURLValid(this string source)
{
Uri uriResult;
return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
}
用法:
string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
//valid process
}
更新:(单行代码)感谢@GoClimbColorado
public static bool CheckURLValid(this string source) => Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps;
用法:
string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
//valid process
}
这里的所有答案要么允许具有其他方案的URL(例如,file://
,ftp://
),要么拒绝不以http://
或https://
(例如,www.google.com
)开头的人类可读URL,这在处理用户输入时不好。
我是这样做的:
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;
}
用法:
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);
}
输出:
True https://www.google.com/
True http://www.google.com/
True http://www.google.com/
True http://google.com/
False
在Uri.TryCreate
之后,您可以检查Uri.Scheme
以查看它是否为HTTP(s)。
这将返回bool:
Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)
Uri uri = null;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri)
return false;
else
return true;
这里url
是你必须测试的字符串。
试试看:
bool IsValidURL(string URL)
{
string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return Rgx.IsMatch(URL);
}
它将接受这样的URL:
bool passed = Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)