1

我想验证一个 url,它是否存在或抛出页面未找到错误。任何人都可以帮助我如何在 asp.net 中做到这一点。例如,我的网址可能是类似的http://www.stackoverflow.comwww.google.com即它可能包含http://也可能不包含。当我检查时,它应该返回网页有效(如果存在)或页面未找到(如果不存在)

我尝试HttpWebRequest了方法,但它需要“ http://”在网址中。

提前致谢。

4

2 回答 2

4
protected bool CheckUrlExists(string url)
    {
        // If the url does not contain Http. Add it.
        if (!url.Contains("http://"))
        {
            url = "http://" + url;
        }
        try
        {
            var request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "HEAD";
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                return response.StatusCode == HttpStatusCode.OK;
            }
        }
        catch 
        {
            return false;
        }
    }
于 2012-07-26T09:49:34.777 回答
2

尝试这个

using System.Net;
////// Checks the file exists or not.

bool FileExists(string url)
{
   try
   {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";

        //Getting the Web Response.
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;

        //Returns TURE if it Exist
       return (response.StatusCode == HttpStatusCode.OK);
    }
  catch
   {
        //Any exception will returns false. So the URL is Not Exist
        return false;
   }
}

希望我有所帮助

于 2012-07-26T09:38:12.700 回答