Home > other >  Reading and DeserializeObject Response Header using Asp Core 3.1
Reading and DeserializeObject Response Header using Asp Core 3.1

Time:11-12

I'm try to make a paging for collection, I have a Web API and I'm sending paging data into header like total count and next page link so I can read the response header and put it into string as a Json here is my consume code

  public async Task<MultibleValuesHelper> GetAllTags()
    {
        IEnumerable<TagModelDto> tags;
        IEnumerable<PagedDataModel> Header=null;
       
        using (var response = await _httpClient.GetAsync($"tag"))
        {
           
            string apiResponse = await response.Content.ReadAsStringAsync();
            
            if( response.Headers.TryGetValues("X-Pagenation", out var Pagenation))
            {
                var TryHeader = Pagenation.FirstOrDefault();
              
                Header = JsonConvert.DeserializeObject<List<PagedDataModel>>(TryHeader);
            }
            tags = JsonConvert.DeserializeObject<List<TagModelDto>>(apiResponse);
        }
        return new MultibleValuesHelper {
            TagServiceCollection = tags,
            HeaderPagenation = Header
        };
    }

my problem when I'm try to Deserialize header it showen Error :JsonSerializationException: Cannot deserialize the current JSON object So how I can Deserialize Header and put it into IEnumerable Header so I can handle it

CodePudding user response:

Okay the answer is a little bit change in the code we will use PagedDataModel instead List, and here is the full code

public async Task<MultibleValuesHelper> GetAllTags()
{
    IEnumerable<TagModelDto> tags;
    PagedDataModel Header=new PagedDataModel ;
   
    using (var response = await _httpClient.GetAsync($"tag"))
    {
       
        string apiResponse = await response.Content.ReadAsStringAsync();
        
        if( response.Headers.TryGetValues("X-Pagenation", out var Pagenation))
        {
            var TryHeader = Pagenation.FirstOrDefault();
          
            Header = JsonConvert.DeserializeObject<PagedDataModel>(TryHeader);
        }
        tags = JsonConvert.DeserializeObject<List<TagModelDto>>(apiResponse);
    }
    return new MultibleValuesHelper {
        TagServiceCollection = tags,
        HeaderPagenation = Header
    };
}

this is will work Thanks for all of you

  • Related