-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Description
Libraries:
Azure.Security.KeyVault.Secrets
Azure.Security.KeyVault.Keys
Azure.Security.KeyVault.Certificates
When I want to get a secret from the Azure KeyVault secrets I can use these .NET client methods
Sync: https://docs.microsoft.com/en-us/dotnet/api/azure.security.keyvault.secrets.secretclient.getsecret?view=azure-dotnet
Async: https://docs.microsoft.com/en-us/dotnet/api/azure.security.keyvault.secrets.secretclient.getsecretasync?view=azure-dotnet
These methods work fine. But they throw a RequestFailedException when a secret with the specified name is not found.
I believe it is a very useful scenario to check if a secret exists without an exception.
For example, I want to add a confirmation before changing the value for existing secret - "Are you sure you want to override it"?
I use a following code for now
public static async Task<Result<KeyVaultSecret>> TryGetSecretAsync(this SecretClient secretClient, string name)
{
try
{
var secret = await secretClient.GetSecretAsync(name);
return Result<KeyVaultSecret>.Ok(secret.Value);
}
catch (RequestFailedException ex)
{
if (ex.Status == 404)
{
return Result<KeyVaultSecret>.NotFound();
}
throw;
}
}I believe this extension will be useful for other users of the KeyVault SDK.
Thanks