使用API 部署 IoT Edge 部署清单:
using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Net;
namespace deployjson
{
internal class Program
{
private static void Main(string[] args)
{
var iotHubName = "xxxxx.azure-devices.net";
var policyName = "iothubowner";
var key = "2afXNDHCq7DA2WHR2c=";
var token = ConstructToken(iotHubName, policyName, key);
var deviceId = "linux-edge-01";
var result = DeployManifest(iotHubName, deviceId, token);
Console.WriteLine($"Press a key to exit {result}");
Console.ReadKey();
}
private static string DeployManifest(string iotHubName, string deviceId, string token)
{
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", token);
var body = File.ReadAllText("deployment.amd64.json");
var stringContent = new StringContent(body, Encoding.UTF8, "application/json");
var restUriPost = $"https://{iotHubName}/devices/{deviceId}/applyConfigurationContent?api-version=2020-03-13";
using var resultPost = client.PostAsync(restUriPost, stringContent).Result;
return resultPost.StatusCode.ToString();
}
public static string ConstructToken(string iotHubName, string policyName, string key, int expiryInSeconds = 3600)
{
var fromEpochStart = DateTime.UtcNow - new DateTime(1970, 1, 1);
var expiry = Convert.ToString((int)fromEpochStart.TotalSeconds + expiryInSeconds);
var stringToSign = $"{WebUtility.UrlEncode(iotHubName)}\n{expiry}";
var hmac = new HMACSHA256(Convert.FromBase64String(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
var token = $"SharedAccessSignature sr={WebUtility.UrlEncode(iotHubName)}&sig={WebUtility.UrlEncode(signature)}&se={expiry}";
if (!string.IsNullOrEmpty(policyName))
{
token += "&skn=" + policyName;
}
return token;
}
}
}