.NET: Check URL's response status code?

后端 未结 5 2191
时光说笑
时光说笑 2021-02-18 18:36

What\'s the easiest way in .NET to check what status code a web server replies with to a GET request?

Note that I do not need the body of the response. In fact, if possi

5条回答
  •  -上瘾入骨i
    2021-02-18 19:06

    I've ended up with this method which combines Ivan Ferić's answer and with proper exceptional cases support:

    public async Task IsAccessibleAsync (string url)
    {
        if (url == null)
            throw new ArgumentNullException ("url");
    
        if (url.IndexOf (':') < 0)
            url = "http://" + url.TrimStart ('/');
    
        if (!Uri.IsWellFormedUriString (url, UriKind.Absolute))
            return false;
    
        var request = (HttpWebRequest) WebRequest.Create (url);
        request.Method = "HEAD";
    
        try
        {
            using (var response = await request.GetResponseAsync () as HttpWebResponse)
            {
                if (response != null && response.StatusCode == HttpStatusCode.OK)
                    return true;
    
                return false;
            }
        }
        catch (WebException)
        {
            return false;
        }
    }
    

提交回复
热议问题