如何检查字符串是否是有效的HTTP URL?

Lou*_*hys 232 .net c# validation url uri

Uri.IsWellFormedUriStringUri.TryCreate方法,但它们似乎返回true文件路径等.

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

小智 404

尝试此操作来验证HTTP URL(uriName是您要测试的URI):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && uriResult.Scheme == Uri.UriSchemeHttp;
Run Code Online (Sandbox Code Playgroud)

或者,如果您要同时接受HTTP和HTTPS URL(根据J0e3gan的评论):

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

  • 根据@ Fiarr的评论,除了HTTP URL之外,解释HTTPS所需的"小变化"是:`bool result = Uri.TryCreate(uriName,UriKind.Absolute,out uriResult)&& uriResult.Scheme == Uri. UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps;` (10认同)
  • 您可能想要为uriResult添加更多条件.方案== ...特别是https.这取决于你需要什么,但这个小小的改变是我需要它才能完美地为我工作. (7认同)
  • 看起来这种技术在75次测试中失败了22次https://dotnetfiddle.net/XduN3A (7认同)
  • 这应该读取uriResult.Scheme而不是uriName.Scheme?我正在使用TryCreate的重载,它接受String而不是Uri作为它的第一个参数. (6认同)
  • 对于像_http:// abcde_这样的URL,这种方式会失败.它说这是一个有效的URL. (3认同)
  • 或者在.NET Core中,C#7(Uri类中的常量消失了......):`bool result = Uri.TryCreate(uriName,UriKind.Absolute,out Uri uriResult)&&(uriResult.Scheme ==" http"|| uriResult.Scheme =="https");` (3认同)
  • @KailashP是对的 - 如果没有额外的检查,我认为我不喜欢这个代码:`&& uriResult!= null`! (3认同)

Kis*_*ath 85

此方法在http和https中均可正常工作.只需一行:)

if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute))
Run Code Online (Sandbox Code Playgroud)

MSDN:IsWellFormedUriString

  • 对于非HTTP URI(即[任何其他方案](https://msdn.microsoft.com/en-us/library/system.uri.scheme(v = vs.110).aspx),这将返回true,例如`file://`或`ldap://`.这个解决方案应该与对方案的检查相结合 - 例如`if(uri.Scheme!= Uri.UriSchemeHttp && uri.Scheme!= Uri.UriSchemeHttps).. .` (11认同)
  • @Squiggle这正是我想要检查的内容,***所有***因为我正在制作下载程序.所以,这个答案对我来说是最好的方法. (3认同)

Erç*_*ğlu 22

    public static bool CheckURLValid(this string source)
    {
        Uri uriResult;
        return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
    }
Run Code Online (Sandbox Code Playgroud)

用法:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
Run Code Online (Sandbox Code Playgroud)

更新:(单行代码)感谢@GoClimbColorado

public static bool CheckURLValid(this string source) => Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps;
Run Code Online (Sandbox Code Playgroud)

用法:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
Run Code Online (Sandbox Code Playgroud)

  • @ZauberParacelsus"www.google.com"无效.URL均值应以"http","ftp","file"等开头.字符串应为"http:// www.google.com",不含空格 (5认同)

Mar*_*cas 12

试试看:

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

它将接受这样的 URL:

  • http(s)://www.example.com
  • http(s)://stackoverflow.example.com
  • http(s)://www.example.com/page
  • http(s)://www.example.com/page?id=1&product=2
  • http(s)://www.example.com/page#start
  • http(s)://www.example.com:8080
  • http(s)://127.0.0.1
  • 127.0.0.1
  • www.example.com
  • 例子.com


Ahm*_*eed 9

这里所有的答案,或者允许与其他方案的网址(例如file://,ftp://)或拒绝人类可读的网址不启动http://https://(例如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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

True    https://www.google.com/
True    http://www.google.com/
True    http://www.google.com/
True    http://google.com/
False
Run Code Online (Sandbox Code Playgroud)


Mis*_*ble 5

之后Uri.TryCreate你可以查看Uri.Scheme它是否是HTTP(s).


Ife*_*kwu 5

作为使用正则表达式的另一种方法,此代码使用Uri.TryCreate每个 OP,但随后还会检查结果以确保其方案是 http 或 https 之一:

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