我需要对以下网站网址返回 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/