c# - 使用Azure Batch Restful API创建azure批处理池,遇到异常

标签 c# rest azure webclient azure-batch

我正在尝试使用 RESTful API 创建一个池。我知道有用于批处理服务的 C# 库,但为了以编程方式指定子网 id,我必须使用 RESTful API 来创建它,我在 this MSDN article 中读到过它。 .

我的帖子 URI 遵循格式

https://{帐户名称}.{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"}

at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request) at System.Net.WebClient.UploadString(Uri address, String method, String data)
at System.Net.WebClient.UploadString(String address, String method, String data) at batchServer.Program.createPool(String poolId, String machineSize, String osFamily, String subnetId, String commandLine, Int32 numberOfMachine, List`1 resourceFiles) in C:\Users\fange\Downloads\ALMTest-master\batchServer\Program.cs:line 61

谁能帮帮我吗?

最佳答案

根据您提供的代码,我在我这边测试并重现了这个问题。调试代码时,可以发现详细错误如下:

据我所知,一些常见的 header 被认为是受限制的,受到系统的保护,不能在 WebHeaderCollection 对象中设置或更改,您可以按照此 tutorial 进行操作。 .

为了一种简单的方法,我建议您可以使用 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;
}

您可以关注的详细信息Authentication via Shared Key .

关于c# - 使用Azure Batch Restful API创建azure批处理池,遇到异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39231734/

相关文章:

azure - Azure SQL 数据库是否支持内存优化表?

c# - 如何确定字符串中是否包含此 SpriteFont 无法解析的字符?

c# - 是否可以使用 Rosyln 或 Resharper 来检测可能的 DivideByZero 案例?

java - Jersey Rest 服务无法使用 Json 注释工作

ios - 用于通用 rest API 的 NSData 对象中的 JSON

c# - Azure 上的用户授权

将服务器部署到 Azure 后,Azure 数据库变为只读

c# - 我无法连接以测试使用 TcpListener 启动的本地服务器

c# - 为什么我能够使用 AES 256 位解密来解密修改后的加密数据

linux - RAD SERVER 10.4.1 "E2597(SystemPath)\ld-linux.exe: error: cannot find -lz "部署到 Linux 64