How to get an specific header value from the HttpResponseMessage

前端 未结 7 1815
挽巷
挽巷 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条回答
  •  萌比男神i
    2020-12-16 09:40

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

    IEnumerable 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;
    

提交回复
热议问题