URL validation no working

Jassim Al Rahma 1,556 Reputation points
2021-05-23T18:01:05.7+00:00

Hi,

Why below validation return valid for invalid URLs?

if (!Uri.IsWellFormedUriString("microsoft", UriKind.RelativeOrAbsolute))
{
    Console.WriteLine("Invalid URL");
}
else
{
    Console.WriteLine("Valid URL");
}

I want only the following to be valid:

Thanks,
Jassim

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Cheong00 3,476 Reputation points
    2021-05-24T01:25:21.417+00:00

    Check the URI kind to be Absolute only then.

    The method is treating the path you passed as relative path, that's why it can be validated without problem.


  2. Timon Yang-MSFT 9,586 Reputation points
    2021-05-24T02:37:41.407+00:00

    This is a valid relative path, in fact, even if you just enter a few letters randomly, it will return the same result.

    In html, we might use code like this:

    <a href="microsoft"">link text</a>  
    

    When you click it, it will open the file named "microsoft" in the same folder. It is no problem to name the file "microsoft".

    This should be stipulated by a certain specification of the Web, and c# is following these specifications.

    Uri.IsWellFormedUriString(String, UriKind) Method


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments