A URI provides a simple and extensible means for identifying a resource, it's nothing more than an identifier and as such it can allow for some characters that are not allowed by URLs as they can be names, locations, or both.
URLS are a subset of URIs which are restricted by the characters they may contain and how those characters are organized. For further information we can reference the RFC.
A URI can be further classified as a locator, a name, or both. The
term “Uniform Resource Locator” (URL) refers to the subset of URIs
that, in addition to identifying a resource, provide a means of
locating the resource by describing its primary access mechanism
(e.g., its network “location”).
In essence all URLs are URIs but not all URIs are URLs. URLs not only tell what something is but also tell you how to get to it. There is a good article on the difference of URIs and URLs written by Daniel Miessler.
As such the behavior you are experiencing is accurate, as it doesn't know for a fact that you are trying to creating a legit URL, but regardless your are creating an accurate URI.
In order to detect if it is a valid URL use the method below from this question.
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;
}
Usage:
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);
}
Output:
True https://www.google.com/
True http://www.google.com/
True http://www.google.com/
True http://google.com/
False
Why do URLs with underscores in them return false from Uri.TryCreate?
Urls/Uris containing underscores will always return false when using Uri.TryCreate. This is due to a modification of the standard
This change required all rule names that formerly
included underscore characters to be renamed with a dash instead.