问题描述
我有一个带有路由指向触发功能的EventHub.
I have an IoTHub with a route that points to an EventHub which triggers a Functions.
我无法从事件对象获取 DeviceId 和其他IoT中心属性,而没有将这些属性显式添加到有效负载中.
I'm having problem getting the DeviceId and other IoT Hub properties from the event object without adding those explicitly to the payload.
如果我将输入类型设置为string
(或自定义类型):
If I set the input type to a string
(or a custom type):
public static void Run(string iotMessage, TraceWriter log) {
log.Info($"C# Event Hub trigger function processed a message: {iotMessage}");
}
我仅获得有效负载,而没有其他任何IoT中心属性,例如 DeviceId , CorrelationId 或 MessageId .
I only get the payload without any other IoT Hub properties like DeviceId, CorrelationId or MessageId.
我尝试将类型设置为EventData
:
public static void Run(EventData iotMessage, TraceWriter log) {
log.Info($"C# Event Hub trigger function processed a message: {JsonConvert.SerializeObject(iotMessage)}");
}
现在,我可以通过两个getter访问IoT Hub属性:Properties和SystemProperties.例如,我可以像这样iotMessage.SystemProperties["iothub-connection-device-id"]
访问DeviceId.但是它不会暴露有效载荷.
Now I can access the IoT Hub properties via two getters: Properties and SystemProperties. For example I can access DeviceId like this iotMessage.SystemProperties["iothub-connection-device-id"]
. But it does not expose the payload.
那我该如何访问IoT中心属性和有效负载?
So how do I access both IoT Hub properties and the payload?
推荐答案
我错过了EventData文档中的任何内容.它具有一个称为GetBytes()的方法,并将主体作为字节数组返回.同时获取IoT中心属性和主体的示例:
I missed a thing in the documentation for EventData. It has a method called GetBytes() and returns the body as a byte array. Example of getting both the IoT Hub properties and the body:
public static async void Run(EventData telemetryMessage, TraceWriter log)
{
var deviceId = GetDeviceId(telemetryMessage);
var payload = GetPayload(telemetryMessage.GetBytes());
log.Info($"C# Event Hub trigger function processed a message. deviceId: { deviceId }, payload: { JsonConvert.SerializeObject(payload) }");
}
private static Payload GetPayload(byte[] body)
{
var json = System.Text.Encoding.UTF8.GetString(body);
return JsonConvert.DeserializeObject<Payload>(json);
}
private static string GetDeviceId(EventData message)
{
return message.SystemProperties["iothub-connection-device-id"].ToString();
}
这篇关于Azure IoT中心,EventHub和功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!