Hello @NickKhoo-7526 , Thanks for reaching out to us!
Please check this C# sample repo where we demonstrate sending the sample message to IoTHub.
In the below code block, please see
ContentType = "application/json", ContentEncoding = Encoding.UTF8.ToString(),
temperature = s_randomGenerator.Next(20, 35);
humidity = s_randomGenerator.Next(60, 80);
string dataBuffer = $"{<!-- -->{\"messageId\":{count},\"temperature\":{temperature},\"humidity\":{humidity}}}";
using var eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer))
{
ContentType = "application/json",
ContentEncoding = Encoding.UTF8.ToString(),
};
const int TemperatureThreshold = 30;
bool tempAlert = temperature > TemperatureThreshold;
eventMessage.Properties.Add("temperatureAlert", tempAlert.ToString());
Console.WriteLine($"\t{DateTime.Now}> Sending message: {count}, data: [{dataBuffer}]");
await _deviceClient.SendEventAsync(eventMessage);
The IoTHub documentation has already provided these tutorials and samples in the early stages of the document. Please refer to one of those.
Updated:
In order for IoT Hub to know whether the message can be routed based on its body contents, the message must contain specific headers which describe the content and encoding of its body. In particular, messages must have both these headers for routing on message body to work:
- Content type of "application/json"
- Content encoding must match one of:
- "utf-8"
- "utf-16"
- "utf-32"
If you are using the Azure IoT Device SDKs, it is pretty straightforward to set the message headers to the required properties. If you are using a third-party protocol library, you can use this table to see how the headers manifest in each of the protocols that IoT Hub supports:
HTTP requires a custom header to account for batched messages;
The message body has to be well-formed JSON in order for IoT Hub to route based on the message body. Messages can still be routed based on message headers regardless of whether the content type/content encoding are present. Content type and content encoding are only required for IoT Hub to route based on the body of the message.
Please also look for IoT Hub message routing: now with routing on message body
Please let us know if you need further help in this matter.