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

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


当前回答

试着验证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);

其他回答

试着验证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);

我创建了这个函数来帮助我进行URL验证,你可以根据自己的喜好定制它,注意这是用python3.10.6编写的

def url_validator(url: str) -> bool:
    """
    use this func to filter out the urls to follow only valid urls
    :param: url
    :type: str
    :return: True if the passed url is valid otherwise return false
    :rtype: bool
    """

    #the following regex is copied from Django source code 
    # to validate a url using regax
    
    regex = re.compile(
        r"^(?:http|ftp)s?://"  # http:// or https://
        r"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|"  # domain...
        r"localhost|"  # localhost...
        r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"  # ...or ip
        r"(?::\d+)?"  # optional port
        r"(?:/?|[/?]\S+)$",
        re.IGNORECASE,
    )


    blocked_sites: list[str] = []

    for site in blocked_sites:
        if site in url or site == url:
            return False

    # if none of the above then ensure that the url is valid and then return True otherwise return False
    if re.match(regex, url):
        return True

    return False

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

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

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

MSDN: IsWellFormedUriString

试一试:

bool IsValidURL(string URL)
{
    string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
    Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    return Rgx.IsMatch(URL);
}

它会接受这样的URL:

http (s): / / www . example . com http (s): / / stackoverflow操作。com http (s): / / www . example . com/page http (s): / / www . example . com/page ? id = 1&product = 2 http (s): / / www . example . com/page #开始 http (s) / www . example . com: 8080 http (s): / / 127 . 0 0。1 127 . 0 0。1 www.example.com 操作。com