Is there a faster way to check if an external web page exists?

前端 未结 5 869
感情败类
感情败类 2021-02-07 12:23

I wrote this method to check if a page exists or not:

protected bool PageExists(string url)
{
try
    {
        Uri u = new Uri(url);
        WebRequest w = WebR         


        
5条回答
  •  遥遥无期
    2021-02-07 13:03

    static bool GetCheck(string address)
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
            request.Method = "GET";
            request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
            var response = request.GetResponse();
            return (response.Headers.Count > 0);
        }
        catch
        {
            return false;
        }
    }
    static bool HeadCheck(string address)
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
            request.Method = "HEAD";
            request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
            var response = request.GetResponse();
            return (response.Headers.Count > 0);
        }
        catch
        {
            return false;
        }
    }
    

    Beware, certain pages (eg. WCF .svc files) may not return anything from a head request. I know because I'm working around this right now.
    EDIT - I know there are better ways to check the return data than counting headers, but this is a copy/paste from stuff where this is important to us.

提交回复
热议问题