0

使用新的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 管理证书并与我的订阅相关联:

在此处输入图像描述

我究竟做错了什么?

4

2 回答 2

3

这是另一个选项 - 与其上传证书,不如尝试从您的 publishsettings 文件中提取您的管理证书并使用 X509Certificate 的构造函数,该构造函数需要一个字节 []。然后,将该参数传递给 Convert.FromBase64String 的调用结果,将您的管理证书的字符串表示形式从您的 publishsettings 文件传递​​给它。

此外,请查看计算管理客户端而不是云服务管理客户端。目前,该客户端中的计算堆栈具有更多特定功能。下面的代码是这种方法的演示。请注意,我的 _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));
    }
}
于 2014-01-15T22:28:23.973 回答
1

有一个无参数 ListAsync 方法,它是一种扩展方法。尝试导入 Microsoft.WindowsAzure.Management 命名空间(或 Microsoft.WindowsAzure.Management.Compute 命名空间)。一旦你看到无参数 ListAsync 方法,你应该会很好。我还将模拟一些代码以类似于您要完成的工作,并在一天结束时提供更全面的答案。

于 2014-01-15T20:46:54.250 回答