'Value cannot be null. (Parameter 'sharedKeyCredential') when we try to create SAS Uri using GenerateSasUri() method with V12

We are migrating the code to use azure storage v12 client libraries (Azure.Storage.Blobs 12.12.0) from V11. Getting the below mentioned exception when we try to create SAS Uri using GenerateSasUri() method.
Exception: "Value cannot be null. (Parameter 'sharedKeyCredential')"

this.blobContainerClient = new BlobContainerClient(
                new Uri($https://{storageAccountName}.blob.core.windows.net/{containerName}),
                new ManagedIdentityCredential(managedIdentityAppId));

var blobClient = blobContainerClient.GetBlobClient(blobName);

            BlobSasBuilder sasBuilder = new()
            {
                BlobContainerName = containerName,
                BlobName = blobName,
                Resource = "b", 
                StartsOn = DateTime.UtcNow.AddMinutes(-15),
                ExpiresOn = expirationTimeUtc
            };
            sasBuilder.SetPermissions(requestedPermission);            

            return blobClient.GenerateSasUri(sasBuilder);


Solution 1:[1]

Thomas pointed out the cause for this issue. The best to handle in your code is to check whether your blobclinet can able to create the sas using CanGenerateSasUri

this.blobContainerClient = new BlobContainerClient(
                new Uri($https://{storageAccountName}.blob.core.windows.net/{containerName}),
                new ManagedIdentityCredential(managedIdentityAppId));

var blobClient = blobContainerClient.GetBlobClient(blobName);

    // Check whether this BlobClient object has been authorized with Shared Key.
    if (blobClient.CanGenerateSasUri)
    {
        
            BlobSasBuilder sasBuilder = new()
            {
                BlobContainerName = containerName,
                BlobName = blobName,
                Resource = "b", 
                StartsOn = DateTime.UtcNow.AddMinutes(-15),
                ExpiresOn = expirationTimeUtc
            };
            sasBuilder.SetPermissions(requestedPermission);            

            return blobClient.GenerateSasUri(sasBuilder);
    }
    else
    {
        Console.WriteLine(@"BlobClient must be authorized with Shared Key 
                          credentials to create a service SAS.");
        return null;
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jayendran