How to get an specific header value from the HttpResponseMessage

前端 未结 7 1809
挽巷
挽巷 2020-12-16 09:17

I\'m making an HTTP call. My response contains a session code X-BB-SESSION in the header section of the HttpResponseMessage object. How do I get th

相关标签:
7条回答
  • 2020-12-16 09:25

    If someone like method-based queries then you can try:

        var responseValue = response.Headers.FirstOrDefault(i=>i.Key=="X-BB-SESSION").Value.FirstOrDefault();
    
    0 讨论(0)
  • 2020-12-16 09:28

    You are trying to enumerate one header (CacheControl) instead of all the headers, which is strange. To see all the headers, use

    foreach (var value in responseHeadersCollection)
    {
        Debug.WriteLine("CacheControl {0}={1}", value.Name, value.Value);
    }
    

    to get one specific header, convert the Headers to a dictionary and then get then one you want

    Debug.WriteLine(response.Headers.ToDictionary(l=>l.Key,k=>k.Value)["X-BB-SESSION"]);
    

    This will throw an exception if the header is not in the dictionary so you better check it using ContainsKey first

    0 讨论(0)
  • 2020-12-16 09:29

    You can do this more easily now with

    var session = response.GetHeaderValue("X-BB-SESSION");
    

    Method returns null if the header does not exist.

    0 讨论(0)
  • 2020-12-16 09:30

    You should be able to use the TryGetValues method.

    HttpHeaders headers = response.Headers;
    IEnumerable<string> values;
    if (headers.TryGetValues("X-BB-SESSION", out values))
    {
      string session = values.First();
    }
    
    0 讨论(0)
  • 2020-12-16 09:33

    Below Code Block Gives A formatted view of Response Headers

    WebRequest request = WebRequest.Create("https://-------.com"); WebResponse response = request.GetResponse();

            foreach (var headerItem in response.Headers)
            {
    
                IEnumerable<string> values;
                string HeaderItemValue="";
                values = response.Headers.GetValues(headerItem.ToString());
    
                foreach (var valueItem in values)
                {
                    HeaderItemValue = HeaderItemValue + valueItem + ";";                    
                }
    
                Console.WriteLine(headerItem + " : " + HeaderItemValue);
            }
    
    0 讨论(0)
  • 2020-12-16 09:40

    Though Sam's answer is correct. It can be somewhat simplified, and avoid the unneeded variable.

    IEnumerable<string> values;
    string session = string.Empty;
    if (response.Headers.TryGetValues("X-BB-SESSION", out values))
    {
        session = values.FirstOrDefault();
    }
    

    Or, using a single statement with a ternary operator (as commented by @SergeySlepov):

    string session = response.Headers.TryGetValues("X-BB-SESSION", out var values) ? values.FirstOrDefault() : null;
    
    0 讨论(0)
提交回复
热议问题