Uri class 非常脆弱,似乎过度抛出异常
Uri class is very brittle and seems to throw exceptions excessively
我正在写一个 Web 蜘蛛,我注意到 Uri
class 非常脆弱。
很多锚 href
属性都包含 '/'
之类的东西,但是 Uri
class 在很多 is 上都令人窒息。例如:
Uri uri = new Uri("/");
Invalid URI: The format of the URI could not be determined.
显然,我希望我的代码健壮。在 href
值是部分路径的情况下,我使用 Uri
class 使其成为绝对路径。但是窒息就不行了
有没有其他人处理过这个问题。有没有办法让 Uri
class 更可靠一点?
根据维基百科,URI 方案(URL 的协议)不是可选的:
A non-empty scheme component followed by a colon (:), consisting of a sequence of characters beginning with a letter and followed by any combination of letters, digits, plus (+), period (.), or hyphen (-). Although schemes are case-insensitive, the canonical form is lowercase and documents that specify schemes must do so with lowercase letters. Examples of popular schemes include http, https, ftp, mailto, file, data, and irc. URI schemes should be registered with the Internet Assigned Numbers Authority (IANA), although non-registered schemes are used in practice.
因此您的 Uri uri = new Uri("/");
示例代码不符合规则。
这个异常抛出并不过分,因为它阻止你输入一些可验证无效的东西。充其量你可以争论 vexing exceptions, but really it sounds more like boneheaded 个。
System.Uri(string)
的构造函数 documented 仅接受 绝对 URIs,而不是“ 相对 URIs” (更恰当地称为 URI 的 相对引用 ;请参阅 RFC 3986 的第 1.2 和 4.2 节),并且会在遇到诸如 /
的相对引用时抛出异常。
Uri.TryCreate()
正是我要找的。
解析从 Internet 下载的页面时,无法判断 link 将包含什么。由于您不希望每次发现伪造的东西时代码都抛出错误,如果给定的字符串无效,Uri.TryCreate()
只需 returns false
。
我正在写一个 Web 蜘蛛,我注意到 Uri
class 非常脆弱。
很多锚 href
属性都包含 '/'
之类的东西,但是 Uri
class 在很多 is 上都令人窒息。例如:
Uri uri = new Uri("/");
Invalid URI: The format of the URI could not be determined.
显然,我希望我的代码健壮。在 href
值是部分路径的情况下,我使用 Uri
class 使其成为绝对路径。但是窒息就不行了
有没有其他人处理过这个问题。有没有办法让 Uri
class 更可靠一点?
根据维基百科,URI 方案(URL 的协议)不是可选的:
A non-empty scheme component followed by a colon (:), consisting of a sequence of characters beginning with a letter and followed by any combination of letters, digits, plus (+), period (.), or hyphen (-). Although schemes are case-insensitive, the canonical form is lowercase and documents that specify schemes must do so with lowercase letters. Examples of popular schemes include http, https, ftp, mailto, file, data, and irc. URI schemes should be registered with the Internet Assigned Numbers Authority (IANA), although non-registered schemes are used in practice.
因此您的 Uri uri = new Uri("/");
示例代码不符合规则。
这个异常抛出并不过分,因为它阻止你输入一些可验证无效的东西。充其量你可以争论 vexing exceptions, but really it sounds more like boneheaded 个。
System.Uri(string)
的构造函数 documented 仅接受 绝对 URIs,而不是“ 相对 URIs” (更恰当地称为 URI 的 相对引用 ;请参阅 RFC 3986 的第 1.2 和 4.2 节),并且会在遇到诸如 /
的相对引用时抛出异常。
Uri.TryCreate()
正是我要找的。
解析从 Internet 下载的页面时,无法判断 link 将包含什么。由于您不希望每次发现伪造的东西时代码都抛出错误,如果给定的字符串无效,Uri.TryCreate()
只需 returns false
。