private async Task <object> CosmosUpsert(string connectionString, string databaseName, string containerName, object document, string partitionKey) { CosmosClient client = new CosmosClient(connectionString); Database database = client.GetDatabase(databaseName); Container container = database.GetContainer(containerName); var ser = new ObjectSerializer(); using Stream stream = ser.ToStream(document); using ResponseMessage responseMessage = await container.UpsertItemStreamAsync( partitionKey : new PartitionKey(partitionKey), streamPayload : stream); // Item stream operations do not throw exceptions for better performance if (responseMessage.IsSuccessStatusCode) { object streamResponse = ser.FromStream(responseMessage.Content); return(new { Success = true, Document = streamResponse }); } else { return(new { Success = false, Error = new { responseMessage.StatusCode, Message = responseMessage.ErrorMessage } }); } }