0

IM 尝试使用 Windows Azure 服务管理 REST API 参考以编程方式添加管理证书

以下是使用的片段

public async void AddManagmentCertificate(string subscriptionId, string version)
        {
            string hittingurl = "https://management.core.windows.net/{0}/certificates";
            hittingurl = String.Format(hittingurl, "subidgoeshere");
            XmlDocument addcertDoc = await HelperMethods.PostXmlDocument(hittingurl,"2012-03-01");
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(addcertDoc.NameTable);
            nsmgr.AddNamespace("rest", xmlnamespace);
            if (addcertDoc != null)
            {
                XmlNodeList certadded = addcertDoc.SelectNodes("//rest:SubscriptionCertificateThumbprint", nsmgr);

                if (certadded.Count > 0)
                {
                    string thumbprint = certadded[0].InnerXml.ToString();
                    if (String.IsNullOrEmpty(thumbprint))
                    {

                    }
                    else
                    {
                        LoadData();
                    }
                }


            }



        }


 public static async Task<XmlDocument> PostXmlDocument(string hittingUrl,string Version)
        {
            HttpWebRequest request;
            XmlDocument responsebody = new XmlDocument();


            Uri uri = new Uri(hittingUrl);


            request = (HttpWebRequest)HttpWebRequest.Create(uri);

            request.Method = "POST";
            request.Headers.Add("x-ms-version", Version);
            string certpath = HttpContext.Current.Server.MapPath(@"Certificates\epgwin8dashboard.cloudapp.net.cer");

            request.ClientCertificates.Add(X509Certificate2.CreateFromCertFile(certpath));

            request.ContentType = "application/xml";
            request.ContentLength = 0;




            HttpWebResponse webresponse = null;

            try
            {

                webresponse = (HttpWebResponse)await request.GetResponseAsync();


            }
            catch (Exception)
            {

            }

            HttpStatusCode statuscode = webresponse.StatusCode;
            if (webresponse.ContentLength > 0)
            {
                using (XmlReader reader = XmlReader.Create(webresponse.GetResponseStream()))
                {
                    responsebody.Load(reader);


                }
            }

            if (statuscode.Equals(HttpStatusCode.OK))
            {

                return responsebody;

            }
            else
            {
                return null;
            }


        }

请告诉我还有什么需要改进才能使这个工作没有错误

我被 411 错误返回。

4

1 回答 1

1

试试这个代码。我为此创建了一个简单的控制台应用程序。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace StackOverflowAddManagementCertificate
{
    class Program
    {
        private static string requestPayloadFormat =
            @"<SubscriptionCertificate xmlns=""http://schemas.microsoft.com/windowsazure"">
                <SubscriptionCertificatePublicKey>{0}</SubscriptionCertificatePublicKey>
                <SubscriptionCertificateThumbprint>{1}</SubscriptionCertificateThumbprint>
                <SubscriptionCertificateData>{2}</SubscriptionCertificateData>
            </SubscriptionCertificate>";

        private static string subscriptionId = "your subscription id";

        private static string certificateThumbprint = "certificate thumbprint for validating service management API request";

        private static string x_ms_version = "2012-03-01";

        private static string certificateFile = @"full path of the certificate file which needs to be uploaded e.g. D:\mytest1.cer";
        static void Main(string[] args)
        {
            try
            {
                //First read the certificate from certificate store which will be used to authenticate the request.
                X509Store certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                certificateStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certificates = certificateStore.Certificates;
                var matchingCertificates = certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                var managementCert = matchingCertificates[0];

                X509Certificate2 cert = new X509Certificate2(certificateFile);
                var pk = Convert.ToBase64String(cert.GetPublicKey());
                var tp = cert.Thumbprint;
                var rawData = Convert.ToBase64String(cert.RawData);

                var requestBody = string.Format(CultureInfo.InvariantCulture, requestPayloadFormat, pk, tp, rawData);

                var requestBodyBytes = Encoding.UTF8.GetBytes(requestBody);

                string requestUrl = string.Format(CultureInfo.InvariantCulture,
                                                  "https://management.core.windows.net/{0}/certificates", subscriptionId);

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestUrl);
                req.Method = "POST";
                req.ContentType = "application/xml";
                req.ContentLength = requestBodyBytes.Length;
                req.Headers.Add("x-ms-version", x_ms_version);
                req.ClientCertificates.Add(managementCert);
                using (Stream s = req.GetRequestStream())
                {
                    s.Write(requestBodyBytes, 0, requestBodyBytes.Length);
                }
                using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                {
                    var status = resp.StatusCode;
                }

            }
            catch (WebException webEx)
            {
                var resp = webEx.Response;
                using (var respStream = resp.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(respStream))
                    {
                        string s = sr.ReadToEnd();
                    }
                }

                throw;
            }
        }
    }
}
于 2013-02-14T11:24:45.547 回答