簡體   English   中英

使用Azure Batch Restful API創建Azure批處理池,遇到異常

[英]Create azure batch pool using Azure Batch Restful API, encounter exception

我正在嘗試使用RESTful API創建一個池。 我知道有用於批處理服務的C#庫,但是為了以編程方式指定子網ID,我必須使用RESTful API來創建它,這是我在MSDN文章中了解到的。

我的帖子URI遵循以下格式

https://{account-name}.{region-id}.batch.azure.com/pools?api-version={api-version}

 using (var client = new WebClient())
 {
     client.Headers[HttpRequestHeader.ContentType] = "application/json";
     client.Headers[HttpRequestHeader.Authorization] = "SharedKey <AccountName>:<Signature>";
     client.Headers[HttpRequestHeader.Date] = DateTime.UtcNow.ToString();
     try 
     {
         result = client.UploadString(baseURI, "POST", json);
     } 
     catch(Exception ex)
     {
         Console.WriteLine(ex.StackTrace);
     }
     Console.WriteLine(result);
 }

我發送的json: {"Id":"DotNetPool","vmSize":"small"}

在System.Net.WebClient.UploadStringInternal(Uri地址,String方法,Byte []數據,WebRequest和請求)在System.Net.WebClient.UploadString(Uri地址,String方法,String數據)
在System.Net.WebClient.UploadString(String地址,String方法,String數據)在batchServer.Program.createPool(String poolId,String machineSize,String osFamily,String subnetId,String commandLine,Int32 numberOfMachine,List`1 resourceFiles) :\\ Users \\ fange \\ Downloads \\ ALMTest-master \\ batchServer \\ Program.cs:第61行

誰能幫我嗎?

根據您提供的代碼,我進行了測試,並重現了此問題。 在調試代碼時,您會發現詳細的錯誤,如下所示:

據我所知,一些常見的標頭被認為是受限制的並且受系統保護,並且不能在WebHeaderCollection對象中設置或更改,您可以按照本教程進行操作

以一種簡單的方式,我建議您可以使用HttpWebRequest而不是WebClient來實現您的目的。 這是我的測試代碼,供您使用RESTful API創建池。

public static void CreatePoolViaRestAPI(string baseUrl, string batchAccountName, string batchAccountKey,string jsonData)
{
    string verb = "POST";
    string apiVersion= "2016-07-01.3.1";
    string ocpDate= DateTime.UtcNow.ToString("R");
    string contentType = "application/json; odata=minimalmetadata; charset=utf-8";
    string reqUrl = string.Format("{0}/pools?api-version={1}", baseUrl, apiVersion);

    //construct the request
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(reqUrl);
    request.Method = verb;
    //Set ContentType
    request.ContentType = contentType;
    //Set ocp-date
    request.Headers.Add("ocp-date", ocpDate);
    var buffer = Encoding.UTF8.GetBytes(jsonData);
    request.ContentLength = buffer.Length;

    #region generate the signature
    string CanonicalizedHeaders = string.Format("ocp-date:{0}", ocpDate);
    string CanonicalizedResource = string.Format("/{0}/pools\napi-version:{1}", batchAccountName, apiVersion);
    string stringToSign = string.Format("{0}\n\n\n{1}\n\n{2}\n\n\n\n\n\n\n{3}\n{4}",
        verb,
        buffer.Length,
        contentType,
        CanonicalizedHeaders, CanonicalizedResource);
    //encode the stringToSign
    string signature = EncodeSignStringForSharedKey(stringToSign, batchAccountKey);
    #endregion

    //Set Authorization header
    request.Headers.Add("Authorization", string.Format("SharedKey {0}:{1}", batchAccountName, signature));
    using (var rs = request.GetRequestStream())
    {
        rs.Write(buffer, 0, buffer.Length);
    }

    //send the request and get response
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        Console.WriteLine("Response status code:{0}", response.StatusCode);
    }
}

注意 :cloudServiceConfiguration和virtualMachineConfiguration屬性是互斥的,並且只能指定其中一個屬性。 如果兩者均未指定,則批處理服務將返回錯誤請求(400)。 因此,以上函數中的jsonData參數應如下所示:

"{\"id\":\"DotNetPool\",\"vmSize\":\"small\",\"cloudServiceConfiguration\":{\"osFamily\":\"4\"}}"

更新:

編碼stringToSign的方法如下所示:

public string EncodeSignStringForSharedKey(string stringToSign, string accountKey)
{
    HMACSHA256 h = new HMACSHA256(Convert.FromBase64String(accountKey));
    var byteArray = h.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
    string signature = Convert.ToBase64String(byteArray);
    return signature;
}

您可以通過“通過共享密鑰進行身份驗證”進行詳細了解。

從5.0.0版本開始的Azure Batch C#客戶端SDK可以加入基於Windows Cloud Service的實例的虛擬網絡。 您不需要直接調用REST端點。

- Added support for joining a CloudPool to a virtual network on using the NetworkConfiguration property.

您可以在此處查看5.0.0的ChangeLog: https ://www.nuget.org/packages/Azure.Batch/5.0.0,但請使用最新版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM