1

I'm developing a program who call an API, all works fine but I have to recover some information which are on the response header, how can I recover the information?

I have tried something like : string h = response.Headers; but it doesn't work.

 var client = new RestClient("https://xxxx.com/");

        client.Authenticator = new HttpBasicAuthenticator("user", "password");


        var request = new RestRequest("xx/xx/xx", Method.GET);
        IRestResponse response = client.Execute(request);
        var xml_text = response.Content;
Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
ALDZAFE
  • 15
  • 2
  • 7
  • 2
    Possible duplicate of [Get value from RestSharp response headers](https://stackoverflow.com/questions/23338511/get-value-from-restsharp-response-headers) – Tiago Crizanto Jan 31 '19 at 13:44
  • I have all ready saw this post but it doesn't help me ! – ALDZAFE Jan 31 '19 at 14:01
  • @ALDZAFE where in YOUR code are you trying to access the headers? Also, the procedure in that example clearly lays out how to get the headers list and search for a particular header by name. – Glenn Ferrie Jan 31 '19 at 15:12

1 Answers1

8

I'm pretty sure that response headers in RestSharp are returned as a collection (IList) so declaring h as a string won't work. See the source here. You might want to try and cast the value to a string like this:

foreach (var h in response.Headers)
{
  h.ToString();
}

If you know name of the header you're looking for, you can use a bit of LINQ like what is shown here :

string userId = response.Headers
    .Where(x => x.Name == "userId")
    .Select(x => x.Value)
    .FirstOrDefault().ToString();
user2924019
  • 1,983
  • 4
  • 29
  • 49
db2
  • 195
  • 2
  • 13
  • Thanks for your answer ! I tried with `response.Headers.ToString();` and the result is `System.Collections.Generic.List 1[RestSharp.Parameter]` and that's not what I execpt. I don't know the name of the header ... – ALDZAFE Jan 31 '19 at 15:15
  • Because the headers are returned as a collection, you'll probably have to do a `foreach` to get to the values in the headers. I updated the answer. – db2 Jan 31 '19 at 15:20
  • Perfect, thanks. I avoided the LINQ with a simple IF...THEN. Declare the variable outside, then 'if (h.ToString().StartsWith("userId") ) { USERId = h.ToString(); }' – Edward Jan 10 '22 at 15:30
  • @Edward why avoid the LINQ expression though? It's much cleaner and more concise, and doesn't pollute scope with potentially useless variables. – db2 Jan 10 '22 at 16:13