【问题标题】:How to get Azure IoT Hub Device's connection string programatically using .Net C#如何使用 .Net C# 以编程方式获取 Azure IoT 中心设备的连接字符串
【发布时间】:2023-02-13 19:15:03
【问题描述】:
我有一个场景需要通过使用 .NET C# 以编程方式传递设备 ID 来获取 Azure IoT 中心设备的连接字符串。
我们可以使用 Microsoft.Azure.Devices、Microsoft.Azure.Devices.Client 包使用连接字符串连接到 Azure IoT Hub,我们可以向设备发送消息。
但是,就我而言,我必须向客户提供设备访问策略,以使用该设备的连接字符串将消息直接发送到该设备/设备 ID。
在这里,我需要通过在 .NET C# 中以编程方式传递设备 ID 来获取主要和次要连接字符串。
【问题讨论】:
标签:
c#
.net
azure-iot-hub
azure-iot-sdk
【解决方案1】:
我按照以下步骤使用设备连接字符串将消息直接发送到该设备/设备 ID,并获取主连接字符串和辅助连接字符串。
- 在 visual studio 代码中输入以下代码。
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:](https://i.imgur.com/WEITVuN.png)");
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" );
}
}
}
}
- 输入连接到 IoT 中心所需的详细信息。有关详细信息,请参阅编程 Microsoft Azure Service Fabric - Pearsoncmg。