33

I am going to assume the answer is no but.... Is there a way to use WebClient to send the HEAD method and return the headers as a string or something similar?

3 Answers3

30

You are right WebClient does not support this. You can use HttpWebRequest and set the method to HEAD if you want this functionality:

System.Net.WebRequest request = System.Net.WebRequest.Create(uri);
request.Method = "HEAD";
request.GetResponse();
btlog
  • 4,760
  • 2
  • 29
  • 38
18

Another way is to inherit from WebClient and override GetWebRequest(Uri address).

    public class ExWebClient : WebClient
    {
        public string Method
        {
            get;
            set;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest webRequest = base.GetWebRequest(address);

            if (!string.IsNullOrEmpty(Method))
                webRequest.Method = Method;

            return webRequest;
        }
    }
xrustal
  • 181
  • 1
  • 3
  • 1
    For a newbie, how do I call this overridden class? – bendecko Apr 08 '14 at 10:44
  • `var wc = new ExWebClient();` instead of `var wc = new WebClient();` – tomfanning Sep 05 '16 at 15:16
  • @bendecko because the access modifier is protected you can't call it from outside the class. However you can just create a facade method to call the protected method worst case. Ex: public WebRequest GetWebRequest2(Uri address) { return GetWebRequest(uri); } //Use a better name than GetWebRequest2 please – dyslexicanaboko Jul 09 '18 at 01:01
4

Most web servers that I request from will accept this method. Not every web server does though. IIS6, for example, will honor the request method SOMETIMES.

This is the status code that is returned when a method isn't allowed...

catch (WebException webException)
            {
                    if (webException.Response != null)
                    {
                        //some webservers don't allow the HEAD method...
                        if (((HttpWebResponse) webException.Response).StatusCode == HttpStatusCode.MethodNotAllowed)

Thanks, Mike

arachnode.net
  • 791
  • 5
  • 12