C#,是否有比 IsWellFormedUriString 更好的方法来验证 URL 格式?
是否有更好/更准确/更严格的方法来确定 URL 的格式是否正确?
使用:
bool IsGoodUrl = Uri.IsWellFormedUriString(url, UriKind.Absolute);
无法捕获所有内容。如果我输入 htttp://www.google.com
并运行该过滤器,它就会通过。然后我稍后在调用 WebRequest.Create
时收到 NotSupportedException
。
这个错误的网址也会使其通过以下代码(这是我能找到的唯一其他过滤器):
Uri nUrl = null;
if (Uri.TryCreate(url, UriKind.Absolute, out nUrl))
{
url = nUrl.ToString();
}
Is there a better/more accurate/stricter method/way to find out if a URL is properly formatted?
Using:
bool IsGoodUrl = Uri.IsWellFormedUriString(url, UriKind.Absolute);
Doesn't catch everything. If I type htttp://www.google.com
and run that filter, it passes. Then I get a NotSupportedException
later when calling WebRequest.Create
.
This bad url will also make it past the following code (which is the only other filter I could find):
Uri nUrl = null;
if (Uri.TryCreate(url, UriKind.Absolute, out nUrl))
{
url = nUrl.ToString();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Uri.IsWellFormedUriString("htttp://www.google.com", UriKind.Absolute)
返回 true 的原因是因为它的形式可能是有效的 Uri。 URI 和 URL 不一样。请参阅:URI 和 URL 之间有什么区别?
在您的情况下,我会检查
new Uri("htttp://www.google.com").Scheme
是否等于http
或https
。The reason
Uri.IsWellFormedUriString("htttp://www.google.com", UriKind.Absolute)
returns true is because it is in a form that could be a valid Uri. URI and URL are not the same.See: What's the difference between a URI and a URL?
In your case, I would check that
new Uri("htttp://www.google.com").Scheme
was equal tohttp
orhttps
.从技术上讲,
htttp://www.google.com
是一个格式正确的网址,根据 URL 规范。由于htttp
不是已注册的方案,因此引发了NotSupportedException
。如果 URL 格式不正确,您将收到UriFormatException
。如果您只关心 HTTP(S) URL,那么也只需检查该方案。Technically,
htttp://www.google.com
is a properly formatted URL, according the URL specification. TheNotSupportedException
was thrown becausehtttp
isn't a registered scheme. If it was a poorly-formatted URL, you would have gotten aUriFormatException
. If you just care about HTTP(S) URLs, then just check the scheme as well.@Greg 的解决方案是正确的。但是,您可以使用 URI 进行控制并验证您想要的所有协议(方案)是否有效。
@Greg's solution is correct. However you can steel using URI and validate all protocols (scheme) that you want as valid.
这段代码可以很好地帮助我检查
Textbox
是否具有有效的 URL 格式This Code works fine for me to check a
Textbox
have valid URL format