开发者

How can I get the name of a HttpResponseHeader?

开发者 https://www.devze.com 2023-04-13 06:56 出处:网络
I am able to loop through a response.Headers collection and display the value for each header like this.

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() +开发者_如何学Python " Value is: " + response.Headers[i].ToString());
    }


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.)


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


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


You can just do:

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


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

or

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号