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

C# 如何检查字符串是否为有效的HTTP URL?,c#,.net,validation,url,uri,C#,.net,Validation,Url,Uri,有方法和,但对于文件路径等,它们似乎返回true 如何检查字符串是否是用于输入验证目的的有效(不一定是活动的)HTTP URL?在Uri.TryCreate之后,您可以检查Uri.Scheme以查看它是否为HTTP。尝试此操作以验证HTTP URL(URME是您要测试的Uri): 或者,如果您希望同时接受HTTP和HTTPS URL作为有效URL(根据J0e3gan的评论): 这将返回布尔值: Uri.IsWellFormedUriString(a.GetAttribute("href"), U

有方法和,但对于文件路径等,它们似乎返回
true


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

Uri.TryCreate
之后,您可以检查
Uri.Scheme
以查看它是否为HTTP。

尝试此操作以验证HTTP URL(
URME
是您要测试的Uri):

或者,如果您希望同时接受HTTP和HTTPS URL作为有效URL(根据J0e3gan的评论):


这将返回布尔值:

Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)
这里
url
是您必须测试的字符串

    public static bool CheckURLValid(this string source)
    {
        Uri uriResult;
        return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
    }
用法:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
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);
}
更新:(一行代码)谢谢@gogramporado

用法:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
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);
}

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


MSDN:

这里的所有答案要么允许URL使用其他模式(例如,
文件://
ftp://
),要么拒绝不以
http://
https://
(例如,
www.google.com
)开头的人类可读URL,这在处理用户输入时是不好的

我是这样做的:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
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);
}
用法:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
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);
}
输出:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}
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);
}
Truehttps://www.google.com/
真的http://www.google.com/
真的http://www.google.com/
真的http://google.com/
假的
试试看:

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.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://127.0.0.1
  • 127.0.0.1
  • www.example.com
  • example.com


是否应该读取uriResult.Scheme而不是uriName.Scheme?我正在使用重载来TryCreate,它将字符串而不是Uri作为第一个参数。您可能希望向uriResult添加更多条件。Scheme==。。。特别是https。这取决于你需要它做什么,但我只需要这个小改动就可以让它完美地为我工作。为了澄清@Fiarr的评论,除了HTTP URL之外,还需要考虑HTTPS的“小改动”是:
bool result=Uri.TryCreate(Urime,UriKind.Absolute,out uriResult)&&uriResult.Scheme==Uri.UriSchemeHttp | | uriResult.Scheme==Uri.UriSchemeHttps对于类似URL的URL,这种方式失败。它说这是一个有效的URL。看起来这项技术在我认为OP特别提到的75次测试中失败了22次,他不喜欢Uri.IswellFormedUrString,因为它为文件路径提供了true。您有解决此问题的方法吗?这似乎无法处理www URL。IE:www.google.com显示为无效。@ZauberParacelsus“www.google.com”无效。URL的意思应该以“http”、“ftp”、“file”等开头。字符串应该是“http://www.google.com”,不带空格。今天,out参数可以改进
Uri.TryCreate(source,UriKind.Absolute,out Uri Uri uriResult)&&uriResult.Scheme==Uri.urischemehtps
这对abc这样的随机字符串不起作用,tassdds等。对于非HTTP uri(例如
文件://
ldap://
),这将返回true。此解决方案应与对方案的检查相结合-例如
if(uri.scheme!=uri.UriSchemeHttp&&uri.scheme!=uri.urichemehttps)…
这是RFC3986兼容的吗?@Squiggle这正是我想要它检查的,因为我正在制作下载程序。所以,这个答案对我来说是最好的方法。问题是IswellFormedUrString将末尾的空格作为URL的有效部分呈现。不,它不认为它们是%20s,因为在空格结果之后添加了一个有效的符号无效URL中的“a”-有效的“a”-有效的?!“a”-无效的?!?对于简单的字符串URL验证,我认为这样更好,如果使用“http:\\test.com”而不是“http:\\test.com”,它只会返回false然而,
.TryCreate
足够聪明,可以更正无效的斜杠。但在我的例子中,这个字符串被用于其他地方进行REST调用,并导致异常。null==url检查被严重重复这允许通过像“mooooo”这样的单个单词但是与Uri.iswellFormedUrString结合使用可能会good@Epirocks这是一个很好的观点。问题是
http://mooooooooo实际上,
是一个有效的Uri。因此,在插入“http://”之后,您不能检查
Uri.iswellFormedUrString
如果您以前检查过,任何没有
方案的内容都将被拒绝。可能我们可以做的是检查
s.Contains('.'))
相反。moooooo本身看起来不像url,因为它没有协议。我所做的是取出您的正则表达式匹配调用,并使用IswellFormedUrString进行&&。@Epirocks完全正确!问题是,如果您在添加
http://
之前使用
IswellFormedUrString
,您最终会拒绝类似
如果在添加
http://
后使用它,则
http://mooooooooo
。这就是为什么我建议改为检查字符串是否包含
。这对我来说没关系。我不想接受没有http或https的url。所以我先使用IswellFormedUrString,然后使用yo没有regex.bool-bResult=(Uri.IsWellFormedUriString(s,UriKind.Absolute)和&validhttpur(s,out-uriResult));谢谢你的回答质量较低。请提供一些解释,即使你的代码是不言自明的。根本不要使用regex.IsMatch来验证Url。这可能会杀死cpu。