Uri.TryCreate returns true for any string value?

2019-06-15 01:06发布

问题:

I'm trying to validate a Uri using the Uri.TryCreate method and when I called it with an invalid string, the method returned true. Any ideas why? My code is below:

    private void button1_Click(object sender, EventArgs e)
    {
        Uri tempValue;
        if (Uri.TryCreate("NotAURL", UriKind.RelativeOrAbsolute, out tempValue))
        {
            MessageBox.Show("?");
        }
    }

回答1:

That's a valid relative URL. An example of a invalid URI is:

"http://example.com<>"

If you want to allow only absolute URIs, use UriKind.Absolute.

The example will then fail to parse.