Search code examples
asp.netmongodbazure-cosmosdbblazor-server-sideazure-cosmosdb-mongoapi

How can I fix a "authKeyOrResourceToken value cannot be null" error using CosmosDB in .NET Blazor project?


The Scenario I am currently building a website using .NET Blazor with a MongoDB database hosted in Azure CosmosDB. I am following the code example on the following Microsoft Docs page : https://learn.microsoft.com/en-us/samples/azure-samples/partitionedrepository/repository-pattern-with-azure-cosmos-db-sql-api/

The Problem Having implemented this code, I have run into the following error: System.ArgumentNullException: 'Value cannot be null. (Parameter 'authKeyOrResourceToken | secureAuthKey')' highlighted within the following method:

 public static IServiceCollection AddCosmosDb(this IServiceCollection services, Uri serviceEndpoint,
            string authKey, string databaseName, List<string> collectionName)
        {
            var documentClient = new DocumentClient(serviceEndpoint, authKey, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Ignore,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
            documentClient.OpenAsync().Wait();

            var cosmosDbClientFactory = new CosmosDbClientFactory(databaseName, collectionName, documentClient);
            cosmosDbClientFactory.EnsureDbSetupAsync().Wait();

            services.AddSingleton<ICosmosDbClientFactory>(cosmosDbClientFactory);

            return services;
        }

more specifically the line "var documentClient = new DocumentClient ... " Does anyone have an idea at what I'm doing wrong or where I can look to try and fix this? Any guidance would be appreciated.

I have looked into the problem as best I can and from what I have found on the web it may be something to do with the API that MongoDB uses with CosmosDB. I am not 100% sure though.


Solution

  • DocumentClient is the type used for the NoSQL API SDK which is used to NoSQL (previously known as SQL) API accounts, the document you linked specifically talks about this.

    This is not valid for Mongo API accounts. Mongo API accounts are meant to be used with the Mongo drivers and SDKs.