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

PiZ*_*zL3 10 c# url uri notsupportedexception

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

使用:

bool IsGoodUrl = Uri.IsWellFormedUriString(url, UriKind.Absolute);
Run Code Online (Sandbox Code Playgroud)

不抓住一切.如果我输入htttp://www.google.com并运行该过滤器,它就会通过.然后我NotSupportedException打电话给我WebRequest.Create.

这个错误的网址也会使它超过以下代码(这是我能找到的唯一其他过滤器):

Uri nUrl = null;
if (Uri.TryCreate(url, UriKind.Absolute, out nUrl))
{
    url = nUrl.ToString(); 
}
Run Code Online (Sandbox Code Playgroud)

Gre*_*reg 13

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

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

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


Mar*_*ade 8

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