不幸的是,KeyVault 客户端旨在返回带有 KeyVaultErrorException 的任务,以防不存在机密而不是失败消息\结果。
在您的情况下,它会爆炸,因为当您调用.Result它时,它会在 Task 中解开异常并会破坏执行流程。
在 KeyVault 中检索机密的最佳方法是将逻辑包装在 Try\Catch 块中,如下所示:
try
{
var secret = await client.GetSecretAsync(secretPath);
//... any other logic here ...
}
catch (KeyVaultErrorException kvex)
{
//handle key not found here
}
catch (HttpRequestException ex)
{
//handle any other error here if needed
}
为了更容易使用 keyvault,我通常创建一个类来处理这些逻辑,例如:
public class SecretManager
{
KeyVaultClient client;
public SecretManager(KeyVaultClient client){ this.client = client; }
public Task<string> GetSecretAsync(string secretName){
//here I wrap the logic mentioned above
}
}
.
以上截图来自我的头顶,而不是生产代码的副本
如果您使用上述逻辑,而不是为未找到秘密而抛出异常,您进行适当的异常处理并返回空值或表示未找到秘密的值,那么您将能够像预期的那样解开结果.