Search code examples
c#response-headersgitlab-api

c# HttpResponseMessage - how to get X-Total-Pages from response and use it to get all results without pagination


Hello I'm using this to call to GitLab API:

HttpResponseMessage response = await client.GetAsync(apiPath);

In this response there is headers > results view > X-Total-Pages key

value in visual

How to get its value?


Solution

  • So i wrote this method to get list of tags from GIT API. I used X-Total-Pages instead X-Total and it worked to avoid API pagination results and get it all into on list:

                    {
                        List<Tag> tags = new List<Tag>();
                        List<Tag> one_site_of_tags = new List<Tag>();
                        string apiPath = WhichRepo(repository)[0] + "projects/" + appId + "/repository/tags";
                        HttpResponseMessage response = await client.GetAsync(apiPath);                   
                        string number_tag_sites = response.Headers.FirstOrDefault(x => x.Key == "X-Total-Pages").Value.FirstOrDefault();                    
                       
                        for (int site = 1;
                            site <= Int16.Parse(number_tag_sites);
                            site++)
                        {
                            string apiPath2 = apiPath + "?page=" + site;
                            var content = await client.GetStringAsync(apiPath);
                            one_site_of_tags = JsonConvert.DeserializeObject<List<Tag>>(content);
                            tags.AddRange(one_site_of_tags);
                        }                                        
                        
                        return tags;
                    }