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

本文关键字:客户端 存储 获取 Azure publishsettings 文件 使用 | 更新日期: 2023-09-27 18:04:43

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

如何在c#中完成它?

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

我在下面写了一些代码,并验证了它可以工作。这是基于Wade的文章:用新的。publishsettings文件编程地安装和使用管理证书。然后调用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();