How to get deviceid of message in Azure function t

2019-08-16 15:17发布

问题:

I have an Azure function that is triggered by IOThub. So in the Azure function, I have

public static async Task Run(EventData myIoTHubMessage1, TraceWriter log)

How do I get the device id from the Event Data.

I tried

log.Info("devid="+myIoTHubMessage1.SystemProperties["ConnectionDeviceId"]);

It gave an error saying

The given key was not present in the dictionary.

the following document says that https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-messages-construct

ConnectionDeviceId contains the deviceId. Would anybody know how to retrieve the deviceid from EventData or should I use some other class.

回答1:

You can get device ID from SystemProperties:

public static async Task Run(EventData myIoTHubMessage1, TraceWriter log)
{
    var deviceId = myIoTHubMessage1.SystemProperties["iothub-connection-device-id"];
    // ....
}


回答2:

for (EventData receivedEvent : receivedEvents) {
       String deviceId = (String) receivedEvent.getProperties().get("deviceId");
       log.info("From:" + deviceId);
    }