HttpClient retrieve all headers

2020-02-08 11:03发布

Currently, I am working on API wrapper. If I send a bad Consumer Key, the server will return Status as 403 Forbidden in the header. It will also pass custom headers. How do I actually retrieve these custom headers?

This is the response receive from the server.

Cache-Control: private
Date: Wed,  01 May 2013 14:36:17 GMT
P3P: policyref="/w3c/p3p.xml",  CP="ALL CURa ADMa DEVa OUR IND UNI COM NAV INT STA PRE"
Server: Apache/2.2.23 (Amazon)
Status: 403 Forbidden
X-Error: Invalid consumer key.
X-Error-Code: 152
X-Powered-By: PHP/5.3.20
Connection: keep-alive

I need to retrieve the X-Error and X-Error-Code. Currently, I am using HttpClient class to process the request. If I watch the headers respond under Quick Watch in VS Studio 2012, I could find it like this

((System.Net.Http.Headers.HttpHeaders)(response.Headers)).headerStore["X-Error-Code"].ParsedValue

Is there any other way to do this?

Edit: headerStore is not accessible thru code as this is private field. I only get access to it through the Quick Watch window.

This is my snippet for the request:

var response = await _httpClient.PostAsync("/v3/oauth/request", content);

5条回答
来,给爷笑一个
2楼-- · 2020-02-08 11:30

Well, HttpResponseMessage.Headers returns an HttpResponseHeaders reference, so you should be able to use GetValues()

string error = response.Headers.GetValues("X-Error").FirstOrDefault();
string errorCode = response.Headers.GetValues("X-Error-Code").FirstOrDefault();
查看更多
趁早两清
3楼-- · 2020-02-08 11:43

A bit bulky, but simple to understand..

            System.Diagnostics.Debug.Write("----- CLIENT HEADERS -----" + Environment.NewLine);
            foreach (KeyValuePair<string, IEnumerable<string>> myHeader in myHttpClient.DefaultRequestHeaders)
            {
                System.Diagnostics.Debug.Write(myHeader.Key + Environment.NewLine);
                foreach(string myValue in myHeader.Value)
                {
                    System.Diagnostics.Debug.Write("\t" + myValue + Environment.NewLine);
                }
            }

            System.Diagnostics.Debug.Write("----- MESSAGE HEADERS -----" + Environment.NewLine);
            foreach (KeyValuePair<string, IEnumerable<string>> myHeader in myHttpRequestMessage.Headers)
            {
                System.Diagnostics.Debug.Write(myHeader.Key + Environment.NewLine);
                foreach (string myValue in myHeader.Value)
                {
                    System.Diagnostics.Debug.Write("\t" + myValue + Environment.NewLine);
                }
            }

            System.Diagnostics.Debug.Write("----- CONTENT HEADERS -----" + Environment.NewLine);
            foreach (KeyValuePair<string, IEnumerable<string>> myHeader in myHttpRequestMessage.Content.Headers)
            {
                System.Diagnostics.Debug.Write(myHeader.Key + Environment.NewLine);
                foreach (string myValue in myHeader.Value)
                {
                    System.Diagnostics.Debug.Write("\t" + myValue + Environment.NewLine);
                }
            }
查看更多
爷、活的狠高调
4楼-- · 2020-02-08 11:46

Since the title of the question is "retrieve all headers", I wanted to add an answer in regards to that.

The HttpResponseMessage returned by HttpClient methods has two header properties:

  • HttpResponseMessage.Headers is an HttpResponseHeaders with generic response headers
  • HttpResponseMessage.Content.Headers is an HttpContentHeaders with content-specific headers like Content-Type

Both objects implement IEnumerable<KeyValuePair<string, IEnumerable<string>>, so you can easily combine all the headers with something like this:

var responseMessage = await httpClient.GetAsync(url);
var headers = responseMessage.Headers.Concat(responseMessage.Content.Headers);
查看更多
相关推荐>>
5楼-- · 2020-02-08 11:46

This works for me:

(String[])response.Headers.GetValues("X-Error"))[0]
查看更多
We Are One
6楼-- · 2020-02-08 11:50

Just a gotcha that I found when attempting to find a header that didn't exist. You should use TryGetValues instead of GetValues because at runtime it will throw an exception if the header is not found. You would use something like this code:

IEnumerable<string> cookieHeader; 
response.Headers.TryGetValues("Set-Cookie", out cookieHeader);
查看更多
登录 后发表回答