Rahul
Rahul

Reputation: 1163

Continuation token specified in the request is malformed / Invalid format for continuation token Azure Cosmos DB pagination

I am facing an issue with the implementation of paging in cosmos database using continuation token. First time I am getting first batch of results with continuation token in JSON format, but when I pass back that same token JSON string to cosmos DB for getting next set of results, sometimes it throws "Continuation token specified in the request is malformed" or sometimes "Invalid format for continuation token".

Here is the code -

        QueryRequestOptions queryRequestOptions = new QueryRequestOptions
        {
            MaxItemCount = pageSize
        };

        try
        {
            using (FeedIterator<TOutputDocument> resultSetIterator = _cosmosContainer.GetItemQueryIterator<TOutputDocument>(queryDefinition, continuationToken, queryRequestOptions))
            {
                if (resultSetIterator.HasMoreResults)
                {
                    FeedResponse<TOutputDocument> response = await resultSetIterator.ReadNextAsync();

                    if (response == null)


                    {
                        throw new NullReferenceException($"Unable to get response from cosmos db against query - {query}, container - {nameof(_cosmosContainer)}");
                    }
                    continuationToken = response.ContinuationToken;
                    documents.AddRange(response);
                }
            }
        }
        catch (CosmosException ex)
        { }

Thanks

Upvotes: 1

Views: 1798

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222522

As the error denotes , it seems that the continuation token is null or in invalid format.

If the token is Null,

[{\"token\":null,\"range\":{\"min\":\"05C1DFFFFFFFFC\",\"max\":\"FF\"}}]

Follow the steps mentioned in this issue.

In the case of Invalid token, Try to encode it with Base64 as below

string continuationToken = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(cosmosToken));

Upvotes: 2

Related Questions