c#,是否有比IsWellFormedUriString更好的方法来验证URL格式

本文关键字:方法 验证 URL 格式 更好 是否 IsWellFormedUriString | 更新日期: 2023-09-27 17:49:39

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

使用:

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

不能捕获所有内容。如果我输入htttp://www.google.com并运行该过滤器,它就通过了。然后当调用WebRequest.Create时,我得到一个NotSupportedException

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

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

c#,是否有比IsWellFormedUriString更好的方法来验证URL格式

Uri.IsWellFormedUriString("htttp://www.google.com", UriKind.Absolute)返回true的原因是因为它的形式可能是有效的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并验证您想要的所有协议(方案)是否有效。

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; 
}