URI 提供了一种简单且可扩展的方法来标识资源,它只不过是一个标识符,因此它可以允许一些 URL 不允许的字符,因为它们可以是名称、位置或两者兼而有之。
URLS 是 URI 的子集,受它们可能包含的字符以及这些字符的组织方式限制。如需更多信息,我们可以参考 RFC。
URI 可以进一步分类为定位符、名称或两者。这
术语“统一资源定位器”(URL)是指 URI 的子集
除了识别资源之外,还提供了一种方法
通过描述资源的主要访问机制来定位资源
(例如,它的网络“位置”)。
本质上,所有 URL 都是 URI,但并非所有 URI 都是 URL。 URL 不仅告诉您某物是什么,还告诉您如何访问它。 Daniel Miessler 写了一个good article on the difference of URIs and URLs。
因此,您遇到的行为是准确的,因为它不知道您正在尝试创建合法 URL,但不管您正在创建准确的 URI。
为了检测它是否是有效的 URL,请使用 this question 中的以下方法。
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
为什么带有下划线的 URL 从 Uri.TryCreate 返回 false?
使用 Uri.TryCreate 时,包含下划线的 Urls/Uris 将始终返回 false。这是由于modification of the standard
此更改需要以前的所有规则名称
包括下划线字符,改为用破折号重命名。