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

前端 未结 10 956
栀梦
栀梦 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:30

    Use it.....

    string myString = http//:google.com;
    Uri myUri;
    Uri.TryCreate(myString, UriKind.RelativeOrAbsolute, out myUri);
     if (myUri.IsAbsoluteUri == false)
     {
      MessageBox.Show("Please Input Valid Feed Url");
     }
    
    0 讨论(0)
  • 2020-12-13 12:32

    A shortcut would be to use Uri.IsWellFormedUriString:

    if (Uri.IsWellFormedUriString(myURL, UriKind.RelativeOrAbsolute))
    ...
    
    0 讨论(0)
  • 2020-12-13 12:32

    you can use the function Uri.TryCreate As Panagiotis Kanavos suggested if you like to test and create a url or you can use Uri.IsWellFormedUriString function as suggested by Todd Menier if you just wanted to test the validity of Url. this can by handy if you are just validating user input for now and need to create url some time later in life time of your application.

    **But my post is for the People, like myself :( , still hitting their heads against .net 1.1 **

    both above methods were introduced in .net 2.0 so you guys still have to use try catch method, which, in my opinion, is still far better than using regular expression.

    private bool IsValidHTTPURL(string url)
    {
        bool result = false;
    
        try
        {
            Uri uri = new Uri(url);
    
            result = (uri.Scheme == "http" || uri.Scheme == "https");
        }
        catch (Exception ex) 
        { 
            log.Error("Exception while validating url", ex); 
        }
    
        return result;
    }
    
    0 讨论(0)
  • 2020-12-13 12:34

    I wanted to check if the url also contains a domain extension, it needs to be a valid website url.

    This is what i came up with:

     public static bool IsValidUrl(string url)
            {
                if (string.IsNullOrEmpty(url)) { return false;}
    
                if (!url.StartsWith("http://"))
                {
                    url = "http://" + url;    
                }
    
                Uri outWebsite;
    
                return Uri.TryCreate(url, UriKind.Absolute, out outWebsite) && outWebsite.Host.Replace("www.", "").Split('.').Count() > 1 && outWebsite.HostNameType == UriHostNameType.Dns && outWebsite.Host.Length > outWebsite.Host.LastIndexOf(".") + 1 && 255 >= url.Length;
            }
    

    I've tested the code with linqpad:

        void Main()
    {
            // Errors
            IsValidUrl("www.google/cookie.png").Dump();
            IsValidUrl("1234").Dump();
            IsValidUrl("abcdef").Dump();
            IsValidUrl("abcdef/test.png").Dump();
            IsValidUrl("www.org").Dump();
            IsValidUrl("google").Dump();
            IsValidUrl("google.").Dump();
            IsValidUrl("google/test").Dump();
            IsValidUrl("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0").Dump();
            IsValidUrl("</script><script>alert(9)</script>").Dump();
            IsValidUrl("Accept: application/json, text/javascript, */*; q=0.01").Dump();
            IsValidUrl("DNT: 1").Dump();
    
            Environment.NewLine.Dump();
    
            // Success
            IsValidUrl("google.nl").Dump();
            IsValidUrl("www.google.nl").Dump();
            IsValidUrl("http://google.nl").Dump();
            IsValidUrl("http://www.google.nl").Dump();
    }
    

    Results:

    False False False False False False False False False False False False

    True True True True

    0 讨论(0)
  • 2020-12-13 12:36

    My solution:

    string regular = @"^(ht|f|sf)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$";
    string myString = textBox1.Text.Trim();
    if (Regex.IsMatch(myString, regular))
    {
        MessageBox.Show("it is valide url  " + myString);
    }
    else
    {
        MessageBox.Show("InValide url  " + myString);
    }
    
    0 讨论(0)
  • 2020-12-13 12:38

    Use Uri.TryCreate to create a new Uri object only if your url string is a valid URL. If the string is not a valid URL, TryCreate returns false.

    string myString = "http://someUrl";
    Uri myUri;
    if (Uri.TryCreate(myString, UriKind.RelativeOrAbsolute, out myUri))
    {
        //use the uri here
    }
    

    UPDATE

    TryCreate or the Uri constructor will happily accept strings that may appear invalid, eg "Host: www.stackoverflow.com","Host:%20www.stackoverflow.com" or "chrome:about". In fact, these are perfectly valid URIs that specify a custom scheme instead of "http".

    The documentation of the Uri.Scheme property provides more examples like "gopher:" (anyone remember this?), "news", "mailto", "uuid".

    An application can register itself as a custom protocol handler as described in MSDN or other SO questions, eg How do I register a custom URL protocol in Windows?

    TryCreate doesn't provide a way to restrict itself to specific schemes. The code needs to check the Uri.Scheme property to ensure it contains an acceptable value

    UPDATE 2

    Passing a weird string like "></script><script>alert(9)</script> will return true and construct a relative Uri object. Calling Uri.IsWellFormedOriginalString will return false though. So you probably need to call IsWellFormedOriginalString if you want to ensure that relative Uris are well formed.

    On the other hand, calling TryCreate with UriKind.Absolute will return false in this case.

    Interestingly, Uri.IsWellFormedUriString calls TryCreate internally and then returns the value of IsWellFormedOriginalString if a relative Uri was created.

    0 讨论(0)
提交回复
热议问题