Read response header from WebClient in C#

user3352795 picture user3352795 · Feb 25, 2014 · Viewed 32.7k times · Source

I'm trying to create my first windows client (and this is my fist post her), there shall communicate with a "web services", but i have some trouble to read the response header there is coming back. In my response string do I received a nice JSON document back (and this is my next problem), but i'm not able to "see/read" the header in the response, only the body.

Below is the code i'm using.

        WebClient MyClient = new WebClient();
        MyClient.Headers.Add("Content-Type", "application/json");
        MyClient.Headers.Add("User-Agent", "DIMS /0.1 +http://www.xxx.dk");
        var urlstring = "http://api.xxx.com/users/" + Username.Text;
        string response = MyClient.DownloadString(urlstring.ToString());

Answer

RMazitov picture RMazitov · Sep 8, 2015

You can use WebClient.ResponseHeaders like this:

// Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
WebHeaderCollection myWebHeaderCollection = myWebClient.ResponseHeaders;

Console.WriteLine("\nDisplaying the response headers\n");
// Loop through the ResponseHeaders and display the header name/value pairs. 
for (int i=0; i < myWebHeaderCollection.Count; i++)             
    Console.WriteLine ("\t" + myWebHeaderCollection.GetKey(i) + " = " + myWebHeaderCollection.Get(i));

From https://msdn.microsoft.com/en-us/library/system.net.webclient.responseheaders(v=vs.110).aspx