Azure IoT: send messages with C#

Azure IoT: send messages with C#


  • You must have created an IoT Hub in Azure.
  • You must have created a device in your created Azure IoT Hub.
  • You need the connection string your IoT Hub device (IoT Hub -> Devices -> Select Device -> Configurations)


To use the DeviceClient, which opens the connection to your Azure IoT Hub, you need the NuGet package Microsoft.Azure.Devices.Client

<PackageReference Include="Microsoft.Azure.Devices.Client" Version="1.21.1" />


The following snippet shows a simple class that sends serialized data (class instances) to the Azure IoT Hub.

The connection string and the device id are required to guarantee uniqueness. With the Azure IoT Hub, the connection string is always at the device level. In this way, the Azure IoT Hub guarantees the identity of the device.

The example uses an interface (IIoTHubMessage) for generic constraints. So to the send method cannot be passed every kind of instance, but only classes that implement this specific interface.

// Interface to provide generic constraints
public interface IIoTHubMessage { }

// Message class for temperature values
public class TemperatureStatusMessage : IIoTHubMessage
	public double Value {get;set;}

// Service class to communicate with the Azure IoT Hub
public class IoTHubServices
	private readonly DeviceClient _deviceClient;
	private readonly string _deviceId;

	// Creates the service class instance with your IoTHub connection string and your unique device id
	public IoTHubService(string connectionString, string deviceId)
		_deviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Amqp); // use AMQP
		_deviceId = deviceId;

	// sends messages to IoT Hub - generic constraint to send only specific message types
	public async Task SendAsync<TMessage>(TMessage message) where IIoTHubMessage, class
		string serializedMessage = JsonConvert.SerializeObject(message);
		Message iotHubMessage = new Message(Encoding.UTF8.GetBytes(serializedMessage));

		await _deviceClient.SendEventAsync(iotHubMessage);

The message is then sent via AMQP as Json body to the Azure IoT Hub.

Consume Messages

The message can now be consumed on Azure IoT Hub in different ways:

  • An Azure Function is triggered that processes the message.
  • With the help of Stream Analaytics the message can be evaluated.
  • The Azure IoT Hub offers (a rather expensive) possibility to store the message directly in AVRO or JSON format on an Azure storage. This can also be easily implemented with an Azure Function.
  • The message can be forwarded to an Azure Event Hub to be forwarded to different brokers or consumers.