Search code examples
c#asp.netvalidationurlhttp-redirect

How to check valid URL address?


I have simple code, which gets the URL path and redirect to this URL:

 private void Redirect(String path)
    {

        Uri validatedUri = null;
        var result = Uri.TryCreate(HelpURL + path, UriKind.Absolute, out validatedUri);
        if (result&&validatedUri!=null)
        {
            var wellFormed = Uri.IsWellFormedUriString(HelpURL + path, UriKind.Absolute);
            if(wellFormed)
            {
                Response.Write("Redirect to: " + HelpURL + path);
                Response.AddHeader("REFRESH", "1;URL=" + HelpURL + path);
            }
            else //error
            {
                Response.Write(String.Format("Validation Uri error!", path));
            }

        }
        else 
        {
Response.Write(String.Format("Validation Uri error!", path));
        }                                        
    }

Example of Url:http://web-server/SomeSystemindex.html. It is not valid address, but: at my code result is true, wellFormed is true too!

How to validate URL address?

P.S. HelpUrl+path=http://web-server/SomeSystemindex.html for this case. Where HelpUrl is 'http://web-server/SomeSystem', and path=index.html

P.P.S. I do as Martin says- create connection and check the status code.

  HttpWebRequest req = WebRequest.Create(HelpURL + path) as HttpWebRequest;
                req.UseDefaultCredentials = true;
                req.PreAuthenticate = true;
                req.Credentials = CredentialCache.DefaultCredentials;
                
                var statusCode= ((HttpWebResponse)req.GetResponse()).StatusCode;

                if (statusCode == HttpStatusCode.NotFound)
                    isValid = false;
                else if (statusCode == HttpStatusCode.Gone)
                    isValid = false;
                else
                {
                    isValid = true;
                }

Solution

  • As far as I know, the only way to determine whether an address is valid or not, is by opening a connection. If the connection lives, the address is valid. If not, the connection is not valid. There are some tricks to filter out bad URL's, but to know whether an adress is valid, you need to open a connection.

    An example has already been posted on StackOverflow here

    Or here:

        URL url;
        URL wrongUrl;
        try {
            url = new URL("http://google.com");
            wrongUrl = new URL( "http://notavalidurlihope.com");
            HttpURLConnection con = (HttpURLConnection ) url.openConnection();
            System.out.println(con.getResponseCode());
            HttpURLConnection con2 = (HttpURLConnection ) wrongUrl.openConnection();
            System.out.println(con2.getResponseCode());
        } catch (IOException e) {
            System.out.println("Error connecting");
        }
    

    Note: Do disconnect afterwards

    output:

    200
    Error connecting