Gohawks
Gohawks

Reputation: 481

Cosmos always gets 404 when doing container.ReadItemAsync even though the item is there

I am pulling my hair out for this weird error. I have created an azure cosmosdb and manually inserted an item in the container and then query it from C# code:

        public async Task<T> ReadAsync<T>(string documentId, string collectionName, string partitionKey)
            where T : class
        {
            Requires.NotNullOrWhiteSpace(documentId, nameof(documentId));
            Requires.NotNullOrWhiteSpace(collectionName, nameof(collectionName));

            return await this.PerformActionAsync(
                $"ReadAsync {documentId}. Collection: {collectionName}.",
                async client =>
                {
                    try
                    {
                        Container container = client.GetDatabase(this.cosmosDbDatabaseName).GetContainer(collectionName);
                        ItemResponse<T> response = await container.ReadItemAsync<T>(id: documentId, partitionKey: new PartitionKey(partitionKey)).ConfigureAwait(true);
                        return response.Resource;
                    }
                    catch (CosmosException ex)
                    {
                        if (ex.StatusCode == HttpStatusCode.NotFound)
                        {
                            resultStatus = NotFound;
                            return null;
                        }

                        resultStatus = Exception;
                        throw new Exception("The server encountered an internal error. Please retry the request.");
                    }
   

The code always returns 404 NotFound! But I can see the item in the container from DataExplorer!

Can anyone shed some light on me? Much appreciated.

Thanks!

Upvotes: 0

Views: 5010

Answers (1)

Gohawks
Gohawks

Reputation: 481

The reason was that I got confused by partitionKey, which should be the value of the partitionKey!

Upvotes: 2

Related Questions