A better way to validate URL in C# than try-catch?

前端 未结 10 967
栀梦
栀梦 2020-12-13 12:08

I\'m building an application to retrieve an image from internet. Even though it works fine, it is slow (on wrong given URL) when using try-catch statements in the applicatio

10条回答
  •  借酒劲吻你
    2020-12-13 12:56

    Some examples when using Uri to test a valid URL fails

    Uri myUri = null;
    if (Uri.TryCreate("Host: www.stackoverflow.com", UriKind.Absolute, out myUri))
    {
    }
    
      myUri = null;
    if (Uri.TryCreate("Accept: application/json, text/javascript, */*; q=0.01", UriKind.Absolute, out myUri))
    {
    }
    
      myUri = null;
    if (Uri.TryCreate("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0", UriKind.Absolute, out myUri))
    {
    }
    
      myUri = null;
    if (Uri.TryCreate("DNT: 1", UriKind.Absolute, out myUri))
    {
    }
    

    I Was surprised to have all this nonsense appear in my listview after validating with the above. But it all passes the validation test.

    Now I add the following after the above validation

    url = url.ToLower();
    if (url.StartsWith("http://") || url.StartsWith("https://")) return true;
    

提交回复
热议问题