如何检查 uri 字符串是否有效

如何检查 Uri 字符串是否有效(您可以将其提供给 Uri 构造函数) ?

到目前为止,我只有以下几点建议,但出于显而易见的原因,我宁愿选择一种不那么粗暴的方式:

    Boolean IsValidUri(String uri)
{
try
{
new Uri(uri);
return true;
}
catch
{
return false;
}
}

我试过 Uri.IsWellFormedUriString,但它似乎并不喜欢所有可以抛给构造函数的东西,例如:

String test = @"C:\File.txt";
Console.WriteLine("Uri.IsWellFormedUriString says: {0}", Uri.IsWellFormedUriString(test, UriKind.RelativeOrAbsolute));
Console.WriteLine("IsValidUri says: {0}", IsValidUri(test));

产出将是:

Uri.IsWellFormedUriString says: False
IsValidUri says: True

更新/回答

Uri 构造函数默认使用 kind Absolute。当我尝试使用 Uri 时,这导致了一个差异。TryCreate 和构造函数。如果在构造函数和 TryCreate 中都匹配 UriKind,就会得到预期的结果。

119191 次浏览

In your case the uri argument is an absolute path which refers to a file location, so as per the doc of the method it returns false. Refer to this

A well-formed URI implies conformance with certain RFCs. The local path in your example is not conformant with these. Read more in the IsWellFormedUriString documentation.

A false result from that method does not imply that the Uri class will not be able to parse the input. While the URI input might not be RFC conformant, it still can be a valid URI.

Update: And to answer your question - as the Uri documentation shows, there is a static method called TryCreate that will attempt exactly what you want and return true or false (and the actual Uri instance if true).

Since the accepted answer doesn't provide an explicit example, here is some code to validate URIs in C#:

Uri outUri;


if (Uri.TryCreate("ThisIsAnInvalidAbsoluteURI", UriKind.Absolute, out outUri)
&& (outUri.Scheme == Uri.UriSchemeHttp || outUri.Scheme == Uri.UriSchemeHttps))
{
//Do something with your validated Absolute URI...
}

Assuming we only want to support absolute URI and HTTP requests, here is a function that does what you want:

public static bool IsValidURI(string uri)
{
if (!Uri.IsWellFormedUriString(uri, UriKind.Absolute))
return false;
Uri tmp;
if (!Uri.TryCreate(uri, UriKind.Absolute, out tmp))
return false;
return tmp.Scheme == Uri.UriSchemeHttp || tmp.Scheme == Uri.UriSchemeHttps;
}

In my case I just wanted to test the uri, I don't want to slow down the application testing the uri.

Boolean IsValidUri(String uri){
return Uri.IsWellFormedUriString(uri, UriKind.Absolute);
}

Try it:

private bool IsValidUrl(string address)
{
return Uri.IsWellFormedUriString(address, UriKind.RelativeOrAbsolute);
}