Search code examples
vb.netazure-keyvault

VB.NET Error after calling Dim secret = Await client.GetSecretAsync


I have an error immediately after calling the third line in the below:

Dim kvUri = $"https://{KEY_VAULT_NAME}.vault.azure.net"

Dim client = New SecretClient(New Uri(kvUri), New DefaultAzureCredential())

Dim secret = Await client.GetSecretAsync(KEY_ID)

KEY_VAULT_NAME and KEY_ID are String and have proper values.

The code is inside Main of a module which is marked as

 Public Async Sub Main()

The error is Object reference not set to an instance of an object.

After a while the secret.Value.Value gets the desired sting but I have trouble understanding why I have the error and how to fix this issue.

I tried Microsoft Documentation and StackOverflow


Solution

  • VB.NET error occurs after calling Dim secret = Await client.GetSecretAsync().

    Use the code below to get the secret value of Azure Key Vault using Visual Basic .NET:

    Code:

    Imports Azure.Identity
    Imports Azure.Security.KeyVault.Secrets
    
    Module Program
        Public Sub Main()
            Dim secretValue = GetSecretAsync().GetAwaiter().GetResult()
            Console.WriteLine($"Secret value: {secretValue}")
        End Sub
    
        Private Async Function GetSecretAsync() As Task(Of String)
            Const KEY_VAULT_NAME As String = "samplevault326"
            Const KEY_NAME As String = "secret1"
            Dim kvUri = $"https://{KEY_VAULT_NAME}.vault.azure.net"
    
            Dim credential = New DefaultAzureCredential()
            Dim client = New SecretClient(New Uri(kvUri), credential)
            Dim secret = Await client.GetSecretAsync(KEY_NAME)
    
            If secret Is Nothing Then
                Console.WriteLine("Secret not found")
                Return Nothing
            Else
                Return secret.Value.Value
            End If
        End Function
    End Module
    

    Ensure you are passing the correct parameters, such as key vault name, secret name, and authenticating with the correct credentials.

    Output:

    Secret value: Welcome!!!
    

    enter image description here

    Reference: Quickstart - Azure Key Vault secrets client library for .NET | Microsoft Learn