1

When I try to initialize the cosmos client (latest sdk version 3.50) in Gateway mode, it throws a null ref exception.

From the stack trace it seems it is unable to find the global endpoint, but an nslookup on the domain name gives a positive result.

Here is my code

var options = new CosmosClientOptions() { 
       ConnectionMode = ConnectionMode.Gateway 
};
 
var cosmosClient = new CosmosClient((endpoint, tokenCredential: tokenCredential, options);
  • I tried with a couple of different instances of CosmosDB with the same result

Expected behavior

  • The error message in the exception should indicate what is wrong with my configuration

Actual behavior

_System.NullReferenceException: 
Object reference not set to an instance of an object.
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetAccountPropertiesHelper.GetOnlyGlobalEndpointAsync()
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetAccountPropertiesHelper.GetAccountPropertiesAsync()_

Environment summary

  • SDK Version: 3.50
  • OS Version (e.g. Windows, Linux, MacOSX) Windows Server

Additional context

  • This is the stack trace I get:
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetAccountPropertiesHelper.GetOnlyGlobalEndpointAsync()
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetAccountPropertiesHelper.GetAccountPropertiesAsync()
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetDatabaseAccountFromAnyLocationsAsync(Uri defaultEndpoint, IList`1 locations, IList`1 accountInitializationCustomEndpoints, Func`2 getDatabaseAccountFn, CancellationToken cancellationToken)
   at Microsoft.Azure.Cosmos.GatewayAccountReader.InitializeReaderAsync()
   at Microsoft.Azure.Cosmos.CosmosAccountServiceConfiguration.InitializeAsync()
   at Microsoft.Azure.Cosmos.DocumentClient.InitializeGatewayConfigurationReaderAsync()
   at Microsoft.Azure.Cosmos.DocumentClient.GetInitializationTaskAsync(IStoreClientFactory storeClientFactory)
   at Microsoft.Azure.Documents.BackoffRetryUtility`1.ExecuteRetryAsync[TParam,TPolicy](Func`1 callbackMethod, Func`3 callbackMethodWithParam, Func`2 callbackMethodWithPolicy, TParam param, IRetryPolicy retryPolicy, IRetryPolicy`1 retryPolicyWithArg, Func`1 inBackoffAlternateCallbackMethod, Func`2 inBackoffAlternateCallbackMethodWithPolicy, TimeSpan minBackoffForInBackoffCallback, CancellationToken cancellationToken, Action`1 preRetryCallback)
   at Microsoft.Azure.Documents.ShouldRetryResult.ThrowIfDoneTrying(ExceptionDispatchInfo capturedException)
   at Microsoft.Azure.Documents.BackoffRetryUtility`1.ExecuteRetryAsync[TParam,TPolicy](Func`1 callbackMethod, Func`3 callbackMethodWithParam, Func`2 callbackMethodWithPolicy, TParam param, IRetryPolicy retryPolicy, IRetryPolicy`1 retryPolicyWithArg, Func`1 inBackoffAlternateCallbackMethod, Func`2 inBackoffAlternateCallbackMethodWithPolicy, TimeSpan minBackoffForInBackoffCallback, CancellationToken cancellationToken, Action`1 preRetryCallback)
   at Microsoft.Azure.Documents.BackoffRetryUtility`1.ExecuteRetryAsync[TParam,TPolicy](Func`1 callbackMethod, Func`3 callbackMethodWithParam, Func`2 callbackMethodWithPolicy, TParam param, IRetryPolicy retryPolicy, IRetryPolicy`1 retryPolicyWithArg, Func`1 inBackoffAlternateCallbackMethod, Func`2 inBackoffAlternateCallbackMethodWithPolicy, TimeSpan minBackoffForInBackoffCallback, CancellationToken cancellationToken, Action`1 preRetryCallback)
   at Microsoft.Azure.Cosmos.AsyncCacheNonBlocking`2.GetAsync(TKey key, Func`2 singleValueInitFunc, Func`2 forceRefresh)
   at Microsoft.Azure.Cosmos.DocumentClient.EnsureValidClientAsync(ITrace trace)
   at Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.EnsureValidClientAsync(RequestMessage request, ITrace trace)
   at Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.SendAsync(RequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler.SendAsync(String resourceUriString, ResourceType resourceType, OperationType operationType, RequestOptions requestOptions, ContainerInternal cosmosContainerCore, FeedRange feedRange, Stream streamPayload, Action`1 requestEnricher, ITrace trace, CancellationToken cancellationToken)
   at Microsoft.Azure.Cosmos.ContainerCore.ProcessItemStreamAsync(Nullable`1 partitionKey, String itemId, Stream streamPayload, OperationType operationType, ItemRequestOptions requestOptions, ITrace trace, Nullable`1 targetResponseSerializationFormat, CancellationToken cancellationToken)
   at Microsoft.Azure.Cosmos.ContainerCore.ReadItemAsync[T](String id, PartitionKey partitionKey, ITrace trace, ItemRequestOptions requestOptions, CancellationToken cancellationToken)
   at Microsoft.Azure.Cosmos.ClientContextCore.RunWithDiagnosticsHelperAsync[TResult](String containerName, String databaseName, OperationType operationType, ITrace trace, Func`2 task, Nullable`1 openTelemetry, RequestOptions requestOptions, Nullable`1 resourceType)
1
  • Hi and welcome to Stack Overflow! Pro tip: I see you worked to give your examples but the formatting didn't come out well. If you are using Markdown mode, try using triple quotes to surround your code blocks and stack traces so that newlines are preserved. Commented May 11 at 10:46

1 Answer 1

0

initialize the cosmos client (latest sdk version 3.50) in Gateway mode, it throws a null ref exception.

To initialize the cosmos client in Gateway mode, i tried this by adding Cosmos DB Built-in Data Contributor role to the Azure Cosmos DB account but as i didn't find that role, i tried with the below approach Key-based authentication which works successfully as shown in the below output. This confirms that Key-based authentication works properly in Gateway mode using SDK version 3.50.0, and avoids the internal NullReferenceException. In Gateway mode, the TokenCredential flow triggers a bug in the endpoint GetOnlyGlobalEndpointAsync, while key-based auth bypasses this path and also Key-based auth does not require RBAC setup.

Code I tried with:

static async Task Main(string[] args)
{
    string endpoint = "https://<accName>.documents.azure.com:443/";
    string primaryKey = "<primaryKey>";

    var options = new CosmosClientOptions
    {
        ConnectionMode = ConnectionMode.Gateway
    };

    try
    {
        Console.WriteLine("Initializing CosmosClient in Gateway mode with key auth...");

        var client = new CosmosClient(endpoint, primaryKey, options);

        var db = await client.CreateDatabaseIfNotExistsAsync("TestDb");

        Console.WriteLine("Client initialized and database created.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception occurred:");
        Console.WriteLine(ex);
    }
}

Output:

Initializing CosmosClient in Gateway mode with key auth...
Client initialized and database created.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.