使用新的Windows Azure SDK for .NET,我想获得所有虚拟机的列表。
拼凑早期的文档,这是我想出的:
// This is a custom cert I made locally. I uploaded it to Azure's Management Certificates and added it to my local computer's cert store, see screenshot below.
X509Certificate2 myCustomCert = await this.GetAzureCert();
var credentials = new CertificateCloudCredentials(mySubscriptionId, myCustomCert);
using (var cloudServiceClient = CloudContext.Clients.CreateCloudServiceManagementClient(credentials))
{
credentials.InitializeServiceClient(cloudServiceClient); // Is this required? The next call fails either way.
// This line fails with exception: "The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription."
var services = await cloudServiceClient.CloudServices.ListAsync(CancellationToken.None);
}
我的第一个想法是证书很糟糕,但我能够使用我的自定义证书成功调用Azure REST API。如您所见,它已正确添加到Azure管理证书并与我的订阅相关联:
我做错了什么?
答案 0 :(得分:3)
这是另一个选项 - 而不是上传证书,尝试从您的publishsettings文件中提取管理证书,并使用带有byte []的X509Certificate构造函数。然后,将该参数传递给Convert.FromBase64String的调用结果,并从您的publishsettings文件中传递管理证书的字符串表示形式。
另外,请查看Compute管理客户端而不是Cloud Service Management客户端。此时,该客户端中的计算堆栈有更多特定功能。下面的代码演示了这种方法。注意,我的_subscriptionId和_managementCert字段都是字符串,我只是将它们硬编码为我的publishsettings文件中的值,如上所述。
public async static void ListVms()
{
using (var client = new ComputeManagementClient(
new CertificateCloudCredentials(_subscriptionId,
new X509Certificate2(Convert.FromBase64String(_managementCert)))
))
{
var result = await client.HostedServices.ListAsync();
result.ToList().ForEach(x => Console.WriteLine(x.ServiceName));
}
}
答案 1 :(得分:1)
有一个无参数的ListAsync方法,它是一种扩展方法。尝试导入Microsoft.WindowsAzure.Management命名空间(或Microsoft.WindowsAzure.Management.Compute命名空间)。一旦你看到无参数的ListAsync方法,你应该是好的。我还会模拟一些代码,使其与您想要完成的内容类似,并在当天结束时提供更全面的答案。