这是Uri。IsWellFormedUriString和Uri。TryCreate方法,但它们似乎为文件路径返回true,等等。

我如何检查字符串是否是一个有效的(不一定是活动的)HTTP URL用于输入验证目的?


当前回答

这里的所有答案要么允许使用其他方案的url(例如,file://, ftp://)),要么拒绝以http://或https://开头的人类可读的url(例如,www.google.com),这在处理用户输入时并不好。

我是这样做的:

public static bool ValidHttpURL(string s, out Uri resultURI)
{
    if (!Regex.IsMatch(s, @"^https?:\/\/", RegexOptions.IgnoreCase))
        s = "http://" + s;

    if (Uri.TryCreate(s, UriKind.Absolute, out resultURI))
        return (resultURI.Scheme == Uri.UriSchemeHttp || 
                resultURI.Scheme == Uri.UriSchemeHttps);

    return false;
}

用法:

string[] inputs = new[] {
                          "https://www.google.com",
                          "http://www.google.com",
                          "www.google.com",
                          "google.com",
                          "javascript:alert('Hack me!')"
                        };
foreach (string s in inputs)
{
    Uri uriResult;
    bool result = ValidHttpURL(s, out uriResult);
    Console.WriteLine(result + "\t" + uriResult?.AbsoluteUri);
}

输出:

True    https://www.google.com/
True    http://www.google.com/
True    http://www.google.com/
True    http://google.com/
False

其他回答

在Uri。TryCreate你可以检查Uri。Scheme查看它是否HTTP(s)。

此方法在http和https中都可以正常工作。只有一行:)

if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute))

MSDN: IsWellFormedUriString

试着验证HTTP url (uriName是你想测试的URI):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && uriResult.Scheme == Uri.UriSchemeHttp;

或者,如果你想同时接受有效的HTTP和HTTPS url(根据J0e3gan的评论):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

返回bool值:

Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)

作为使用正则表达式的另一种方法,这段代码使用Uri。TryCreate每个OP,但也检查结果,以确保它的Scheme是http或https之一:

bool passed =
  Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult)
    && (uriResult.Scheme == Uri.UriSchemeHttp
      || uriResult.Scheme == Uri.UriSchemeHttps);