C#,有没有比IsWellFormedUriString更好的方法来validationURL格式?

是否有更好/更准确/更严格的方法/方法来确定URL是否格式正确?

使用:

bool IsGoodUrl = Uri.IsWellFormedUriString(url, UriKind.Absolute); 

不抓住一切。 如果我输入htttp://www.google.com并运行该filter,则会通过。 然后我在调用WebRequest.Create时得到一个NotSupportedException

这个坏url也会使它超过以下代码(这是我能找到的唯一其他filter):

 Uri nUrl = null; if (Uri.TryCreate(url, UriKind.Absolute, out nUrl)) { url = nUrl.ToString(); } 

Uri.IsWellFormedUriString("htttp://www.google.com", UriKind.Absolute)返回true的原因是因为它的forms可能是有效的Uri。 URI和URL不一样。

请参阅: URI和URL之间的区别是什么?

在您的情况下,我会检查new Uri("htttp://www.google.com").Scheme是否等于httphttps

从技术上讲,根据URL规范 , htttp://www.google.com是格式正确的URL 。 抛出NotSupportedException是因为htttp不是注册方案。 如果它是一个格式不正确的URL,你会得到一个UriFormatException 。 如果您只关心HTTP(S)URL,那么也只需检查方案。

@Greg的解决方案是正确的。 但是,您可以使用URI并validation所需的所有协议(方案)是否有效。

 public static bool Url(string p_strValue) { if (Uri.IsWellFormedUriString(p_strValue, UriKind.RelativeOrAbsolute)) { Uri l_strUri = new Uri(p_strValue); return (l_strUri.Scheme == Uri.UriSchemeHttp || l_strUri.Scheme == Uri.UriSchemeHttps); } else { return false; } } 

此代码适用于检查Textbox是否具有有效的URL格式

 if((!string.IsNullOrEmpty(TXBProductionURL.Text)) && (Uri.IsWellFormedUriString(TXBProductionURL.Text, UriKind.Absolute))) { // assign as valid URL isValidProductionURL = true; }