Jive Boogie
Jive Boogie

Reputation: 1265

How can I get the name of a HttpResponseHeader?

I am able to loop through a response.Headers collection and display the value for each header like this.

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(postDest);
//Set up the request with needed properties etc.
HttpWebResponse response = req.GetResponse() as HttpWebResponse;    
for(int i= 0; i < response.Headers.Count; i++)
{
      MessageBox.Show(response.Headers[i].ToString());
}

But how can I get the name Field-Name for each ResponseHeader?

Update:

If I do this I am able to get the Field-Name and the Value.

    for (int i = 0; i < response.Headers.Count; i++)
    {
        MessageBox.Show("Field-Name is: " + response.Headers.GetKey(i).ToString() + " Value is: " + response.Headers[i].ToString());
    }

Upvotes: 2

Views: 5472

Answers (5)

Jordan Rieger
Jordan Rieger

Reputation: 2664

For completeness, I should point out that you can just call .ToString() on the WebHeaderCollection object itself. (Response.Headers.ToString()). Now I don't really recommend this, since the official MSDN comment on the method says:

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

However, looking at the code through ILSpy, it's not doing anything wild, just building up a list of name/value lines in a StringBuilder based on the headers. It does exclude any unnamed headers, but I think those are quite rare. And it's interesting that they didn't go to the trouble of slapping an Obsolete compiler attribute on it (maybe to pass their unit tests?)) So it's probably safe to use. But if you are worried about this, I would recommend the solution posted in the question, which uses direct indexing. Note that direct indexing is faster than the method in the accepted answer, since it doesn't rely on a String key or internal Hashtable (not that performance is likely to be a major concern in this area.)

Upvotes: 2

Berezh
Berezh

Reputation: 937

var values = response.Headers.GetValues("Key")

or

 var values = Enumerable.Empty<string>();
 if (response.Headers.TryGetValues("Key", out values))
 {
     // check values
 }

Upvotes: 0

Icarus
Icarus

Reputation: 63956

You can just do:

foreach (var key in response.Headers.AllKeys)
{
  Console.WriteLine(response.Headers[key]);
}

Upvotes: 0

KreepN
KreepN

Reputation: 8598

foreach (HttpWebResponse v in response.Headers)
{
   v.Headers.Keys.ToString();      
}

Upvotes: 0

krakover
krakover

Reputation: 3029

you can use response.Headers.GetValues(response.Headers.GetKey(i))

Upvotes: 0

Related Questions