Problem with Uri.IsWellFormedUriString RRS feed

  • Question

  • Hello everyone,

    I have a problem with the method System.Uri.IsWellFormedUriString(string, UriKind)
    I use this method to validate a url, so I can open this url in a WebControl. But if I use a url that contains the Symbols '-' AND ' ', so "%20" and "%2D" in the Url-Format, the method returns false.

    An example is "https://www.google.com/?q=test%20test%2Dtest". In my opinion, the url is well formed but why does the method return false?

    string url = "https://www.google.com/?q=test%20test%2Dtest";
    if(Uri.IsWellFormedUriString(url, UriKind.Absolute)
        MessageBox.Show("The url is valid!");
        MessageBox.Show("The url is not valid!");
    //On execute the Messagebox "The url is not valid" appears

    Monday, July 14, 2014 9:03 AM


All replies

  • Hi. The decoded URL is not valid, there shouldn't be a '/' before the '?' and no space between the query parameters.

    Original decoded: https://www.google.com/?q=test test-test

    good version: https://www.google.com?q=test&test-test

    Uri.IsWellFormedUriString will only return true though if uri is fully escaped so that would be:


    You can use HttpUtility.UrlEncode to do that.

    Monday, July 14, 2014 10:17 AM
  • Hi. If I try the url "https://www.google.com/?q=test%20test" the method returns true. Even if I try "https://www.google.com/?q=test%2Dtest" the method return true. That's why I think it's very strange. Why does "%20" and "%2D" not work together in an url?

    And I am using .NET Framework 4.5 if it's necessary

    Monday, July 14, 2014 12:06 PM
  • Hi Masch,

    Per my understanding, I assume you want to judge the URL is correct or not. I think the Uri.IsWellFormedUriString method is not the correct approach. There is some differences between URI and URL. You can see details from http://stackoverflow.com/questions/176264/whats-the-difference-between-a-uri-and-a-url.

    In this case, I think it’s enough to check the domain name is correct. See more http://stackoverflow.com/questions/12386651/how-to-check-if-a-url-is-valid-or-not.

    The below is source code of Uri.IsWellFormedUriString method, you can see detail action of this method. http://referencesource.microsoft.com/#System/net/System/UriExt.cs.  


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. <br/> Click <a href="http://support.microsoft.com/common/survey.aspx?showpage=1&scid=sw%3Ben%3B3559&theme=tech"> HERE</a> to participate the survey.

    • Marked as answer by MaSch212 Thursday, July 17, 2014 6:54 AM
    Thursday, July 17, 2014 6:21 AM
  • Hi,

    thanks for you answer. Now I'm using the TryCreate method and some validation with my own method. It's working fine so far :)

    Thursday, July 17, 2014 6:54 AM