如何使用 .Net C# 以编程方式获取 Azure IoT 中心设备的连接字符串

问题描述 投票:0回答:2

我有一个场景,需要使用 .NET C# 以编程方式传递设备 ID 来获取 Azure IoT 中心设备的连接字符串。

我们可以使用 Microsoft.Azure.Devices、Microsoft.Azure.Devices.Client 包使用连接字符串连接到 Azure IoT 中心,并且可以向设备发送消息。

但是,就我而言,我必须向客户提供设备访问策略,以便使用该设备的连接字符串将消息直接发送到该设备/设备 ID。

enter image description here

在这里,我需要通过在 .NET C# 中以编程方式传递设备 ID 来获取主连接字符串和辅助连接字符串。

c# .net azure-iot-hub azure-iot-sdk
2个回答
4
投票

我按照以下步骤使用设备连接字符串将消息直接发送到该设备/设备 ID,并获取主要和辅助连接字符串。

  • 在 Azure 门户中创建 IoT 中心

enter image description here

  • 在您创建的 IoT 中心创建设备

enter image description here

enter image description here

  • 在 Visual Studio Code 中输入以下代码。
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" );
            }
        }
    }
} 


  • 输入连接到 IoT 中心所需的详细信息。有关更多详细信息,请参阅编程 Microsoft Azure Service Fabric - Pearsoncmg。

enter image description here

enter image description here


0
投票

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.