c# - 最佳 URL 验证

标签 c# asp.net uri

我正在使用如下代码来检查 URL 验证:

 public static bool CheckURLValid(string strURL)
  {
       Uri uriResult;
       return Uri.TryCreate(strURL, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
  }

下面的结果应该全部显示为true,但不知何故它有自己的模式来验证 url:

错误:google.com

:http://www.google.com

错误:https://www.google.com.my/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#newwindow=1&q=check%20if%20valid%20url%20c%23

:https://stackoverflow.com/questions/ask

我正在使用 C#,如何增强此检查 url 验证以使其更准确?

最佳答案

您的 CheckURLValid 返回的正是您告诉它的内容。

问题是要在所有 4 个 URL 上返回 True

错误:google.com

这是一个相对 url,您已指定 UriKind.Absolute,这意味着这是错误的。

错误:https://www.google.com.my/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#newwindow=1&q=check%20if%20valid%20url%20c%23

这是一个 httpS(安全)url,你的方法说

&& uriResult.Scheme == Uri.UriSchemeHttp;

这将限制您只能使用 http 地址(非安全)

要获得您想要的结果,您需要使用以下方法:

public static bool CheckURLValid(string strURL)
{
    Uri uriResult;
    return Uri.TryCreate(strURL, UriKind.RelativeOrAbsolute, out uriResult);
}

另一种方法是使用

Uri.IsWellFormedUriString(strURL, UriKind.RelativeOrAbsolute);

而不是重新实现所有现成的功能。如果你想用自己的 CheckUrlValid 包装它,我会使用以下内容:

public static bool CheckURLValid(string strURL)
{
    return Uri.IsWellFormedUriString(strURL, UriKind.RelativeOrAbsolute); ;
}

主要问题是大多数字符串都是有效的相对 URL,因此我会避免使用 UriKind.RelativeOrAbsolute,因为 google.com 是无效的 URL。大多数 Web 浏览器会自动将 HTTP://添加到字符串中以使其成为有效的 URL。 HTTP://google.com 是一个有效的 url。

关于c# - 最佳 URL 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28049416/

相关文章:

c# - 如何在 App.Config 中写入 URI 字符串

c# - 是否有必要在顶层包装每个异常?

c# - 如何在 ASP.NET 站点中添加 favicon.ico

c# - Linq Expression Slow - 如果可能需要优化

asp.net - IronPython 和 ASP.NET

html - CSS 样式表加载错误

java - Android Studio list URI 未注册

linux - 使用 vala 将 uris 插入 Gtk.Clipboard

c# - 无需安装程序即可发布 Windows 窗体项目

c# - Task.Run 在这里是否合适,包装网络调用?