asp.net C method of checking whether URL is effective

  • 2020-12-07 04:00:39
  • OfStack

We sometimes need to check the validity of the website (URL) entered by the user,


function CheckUrl(str) {
    var RegUrl = new RegExp();
    RegUrl.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\.[A-Za-z0-9-_%&?/.=]+$");
    if (!RegUrl.test(str)) {
        return false;
    }
    return true;
}

Not only from the format, but also to check whether the user input url is really valid. URL can be checked by referring to js regular expressions to verify the url format. There are many ways to check URL effectively. For example, you can use jQuery for checking.

This section presents 1 section of code that uses C# to determine if a url is valid.

Here's how to check the validity of URL:


private bool UrlCheck(string strUrl)
{
    if (!strUrl.Contains("http://") && !strUrl.Contains("https://"))
    {
        strUrl = "http://" + strUrl;
    }
    try
    {
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(strUrl);
        myRequest.Method = "HEAD";
        myRequest.Timeout = 10000;  // timeout 10 seconds 
        HttpWebResponse res = (HttpWebResponse)myRequest.GetResponse();
        return (res.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        return false;
    }
}

When using this method, we only need to pass in Url for validity checking, and remember to add the System.Net namespace when using this method.


if (!UrlCheck("https://www.ofstack.com"))
{
    // Delete operation 
}

Yes, in this site users can enter their own url, but some users do not know is to test or what, input 1 eye can see is not to access the link. So it is necessary to do a check on the user input url, otherwise too many invalid links will affect the weight of the site, more importantly, too many invalid links will affect the experience of other users, because no one wants to click on an invalid link.

Refer to jQuery Ajax,


The following five methods perform the short form of a common Ajax request, which should be used when dealing with complex Ajax requests ().

1.load(url,[data],[callback])

Load the remote HTML file code and insert it into DOM. By default, GET mode is used. When passing parameters, POST mode is automatically converted.

The & # 9702; url: Remote url address to load
The & # 9702; data: key/value data sent to the server
The & # 9702; callback: Callback function on successful load

The sample code is as follows:


// No arguments, no callbacks 
$("#showload").load("load.htm");
// No callbacks 
$("#showload").load("load.htm", { "para": "para-value" });
$("#showload").load("load.htm", { "para": "para-value" },
    function() {
        // To deal with 
    })


Related articles: