使用Azure publishsettings文件获取存储客户端凭据

时间:2013-03-18 16:01:21

标签: c# azure

我有Azure publishsettings文件。现在我必须访问订阅中具有指定名称的存储帐户。

如何在C#中完成它?

1 个答案:

答案 0 :(得分:3)

我在下面写了一些代码并验证它是否有效。它基于韦德的帖子:Programmatically Installing and Using Your Management Certificate with the New .publishsettings File。然后我调用Get Storage Account Keys方法。 Wade的帖子中提到的几个指针:最好创建一个证书并在本地安装它,然后使用它来调用SM API,以便您可以删除.publishsettings文件。它包含您的SM API证书信息,因此您应该删除它或保证它的安全。为简洁起见,此代码不执行安装位,但是Wade的帖子有它。

        var publishSettingsFile =
        @"C:\yourPublishSettingsFilePathGoesHere";

        XDocument xdoc = XDocument.Load(publishSettingsFile);

        var managementCertbase64string =
            xdoc.Descendants("PublishProfile").Single().Attribute("ManagementCertificate").Value;

        var managementCert = new X509Certificate2(
            Convert.FromBase64String(managementCertbase64string));

        // If you have more than one subscription, you'll need to change this
        string subscriptionId = xdoc.Descendants("Subscription").First().Attribute("Id").Value;
        string desiredStorageService = "yourStorageServiceName";

        var req = (HttpWebRequest)WebRequest.Create(
            string.Format("https://management.core.windows.net/{0}/services/storageservices/{1}/keys",
                                            subscriptionId,
                                            desiredStorageService));
        req.Headers["x-ms-version"] = "2012-08-01";
        req.ClientCertificates.Add(managementCert);

        XNamespace xmlns = "http://schemas.microsoft.com/windowsazure";

        XDocument response = XDocument.Load(req.GetResponse().GetResponseStream());

        Console.WriteLine("Primary key: " + response.Descendants(xmlns + "Primary").First().Value);
        Console.WriteLine("Secondary key: " + response.Descendants(xmlns + "Secondary").First().Value);

        Console.Read();