我有一个场景,需要使用 .NET C# 以编程方式传递设备 ID 来获取 Azure IoT 中心设备的连接字符串。
我们可以使用 Microsoft.Azure.Devices、Microsoft.Azure.Devices.Client 包使用连接字符串连接到 Azure IoT 中心,并且可以向设备发送消息。
但是,就我而言,我必须向客户提供设备访问策略,以便使用该设备的连接字符串将消息直接发送到该设备/设备 ID。
在这里,我需要通过在 .NET C# 中以编程方式传递设备 ID 来获取主连接字符串和辅助连接字符串。
我按照以下步骤使用设备连接字符串将消息直接发送到该设备/设备 ID,并获取主要和辅助连接字符串。
using System;
using Microsoft.Azure.Devices;
namespace GetDeviceConnectionString
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter the device id:");
string deviceId = Console.ReadLine();
Console.WriteLine("Enter the connection string for your IoT hub:");
string iotHubConnectionString = Console.ReadLine();
Console.WriteLine("Enter the iotHubName:");
string iotHubName = Console.ReadLine();
RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
var device = registryManager.GetDeviceAsync(deviceId).Result;
Console.WriteLine("Primary key: " + device.Authentication.SymmetricKey.PrimaryKey);
Console.WriteLine("Secondary Key: " + device.Authentication.SymmetricKey.SecondaryKey);
Console.WriteLine(" Primary Connection String : " + " HostName = " + iotHubName+ " .azure - devices.net; DeviceId = " + deviceId+"; SharedAccessKey = " + device.Authentication.SymmetricKey.PrimaryKey);
Console.WriteLine("Secondary Connection String : " + " HostName = " + iotHubName + " .azure - devices.net; DeviceId = " + deviceId + "; SharedAccessKey = " + device.Authentication.SymmetricKey.SecondaryKey);
registryManager.CloseAsync().Wait();
Console.WriteLine("Enter the message to send:");
string message = Console.ReadLine();
ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString);
serviceClient.SendAsync(deviceId, new Microsoft.Azure.Devices.Message(System.Text.Encoding.ASCII.GetBytes(message))).Wait();
Console.WriteLine("Message sent successfully!");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex+"the details are not valid" );
}
}
}
}
IoTHub nuget包中有一个IotHubConnectionStringBuilder类参见。
这可以轻松创建连接,如下所示:
public async Task RegisterDeviceAsync(CancellationToken cancellationToken)
{
//Create a new device with a random guid as Id
var device = new Device(Guid.NewGuid().ToString());
//Add the device to the IoTHub
var createdDevice = await registryManager.AddDeviceAsync(device, cancellationToken);
//Specify the access policy type and what key you wanna use
var accessPolicy = new ServiceAuthenticationWithDeviceSharedAccessPolicyKey(device.Id, createdDevice.Authentication.SymmetricKey.PrimaryKey);
//Create the connectionstring builder
var connectionStringBuilder = IotHubConnectionStringBuilder.Create("HOSTNAME" ,accessPolicy);
//Get the connectionstring
var primaryConnectionString = connectionStringBuilder.ToString();
}