C# - 验证网站 URL。 IsWellFormedUriString 始终返回 true

标签 c# asp.net validation webforms

我需要对以下网站网址返回 true 的检查: 我需要确保以 www 开头的网站。视为真实。 google.com 也应该返回 true。

www.google.com

google.com

http://google.com

http://www.google.com

https://google.com

https://www.google.com

我一直在使用IsWellFormedUriString,但没有取得任何进展。它不断返回 true。我也使用了 Uri.TryCreate 但也无法让它工作。 Stack Overflow 上有很多关于这个主题的内容,但没有一个有效。我一定做错了什么。

这是我的 ValidateUrl 函数:

   public static bool ValidateUrl(string url)
   {
       try
       {
           if (url.Substring(0, 3) != "www." && url.Substring(0, 4) != "http" && url.Substring(0, 5) != "https")
           {
               url = "http://" + url;
           }
           if (Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
           {
               Uri strUri = new Uri(url);
               return true;
           }
           else
           {
               return false;
           }
       }
       catch (Exception exc)
       {
           throw exc;
       }
   }

我这样调用它:

if (ValidateUrl(url) == false) { 
    validationErrors.Add(new Error() 
    { 
        fieldName = "url", 
        errorDescription = "Url is not in correct format." 
    }); 
}

htp:/google.com 返回 true。我知道这个网站上有很多关于这个主题的内容,但昨天我一整天都在努力让它发挥作用,但没有任何效果。

最佳答案

如果您希望用户从数据库复制并粘贴到浏览器中并输入有效的站点,我认为您应该验证网址格式 同时验证url是否存在 例如:

    Uri.IsWellFormedUriString("http://www.google.com", UriKind.Absolute);   

URL 的形式是否正确也是正确的。

    WebRequest request = WebRequest.Create("http://www.google.com");
    try
     {
       request.GetResponse();
     }
   catch (Exception ex)
    {
     throw ex;
   }

如果无法从 url 获取答案,则会返回异常

嗨。

关于C# - 验证网站 URL。 IsWellFormedUriString 始终返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57272162/

相关文章:

c# - 进程外 COM 服务器

c# - 如何导入HL7以获得血液结果并解析以进行患者报告?

javascript - 重新加载以显示新保存的记录时,数据表未正确重新初始化

javascript - Jquery 验证多个条件

javascript - Joi - 针对特定条件使用 'valid'

c# - 如何从 LDAP 路径字符串中提取项目

javascript - Action Method 可以从 ajax post 获取参数中的双值

c# - 在等待新线程产生时调用 thread.sleep()

javascript - Bootstrap Datetimepicker 不在文本字段中显示日期

python - django rest 框架中补丁方法的验证