locked
Send to IoT hub from MVC Web API? RRS feed

  • Question

  • I have created an Azure Api App (using MVC Web API).

    In my controller I have the following POST method:

            public void Post([FromBody]string value)
            {
                // Send message to HemsedalController
                SendCloudToDeviceMessageAsync(value);

            }

            private async static Task SendCloudToDeviceMessageAsync(string message)
            {
                serviceClient = ServiceClient.CreateFromConnectionString(connectionString);

                var commandMessage = new Message(Encoding.ASCII.GetBytes(message));
                await serviceClient.SendAsync("HemsedalController", commandMessage);
            }

    The problem is that execution never returns from serviceClient.SendAsync. I get no message sent to the device and I get no exceptions or errors when running the Web API application from the debugger. I have also tried to encapsulate the call in an try / exception block, but I get no exception or any indication of any error.

    I have tried exactly the same block of code in a console app and then it works fine.

    Any ideas?

    Saturday, July 23, 2016 11:51 AM

Answers

  • To answer my own question. This code works:

            public void Post([FromBody]string message)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(a => SendToDeviceMessage(message));
            }

            // This thread procedure performs the task.
            static void SendToDeviceMessage(Object messageObject)
            {
                string message = (string)messageObject;
                serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
                var commandMessage = new Message(Encoding.ASCII.GetBytes(message));
                serviceClient.SendAsync("HemsedalController", commandMessage).Wait();
            }

    Thursday, August 25, 2016 7:46 AM

All replies

  • I think the issue is related to calling async functions from ASP.NET MVC Web API request handlers.

    Does anyone know how to do this properly?

    Tuesday, July 26, 2016 9:22 AM
  • To answer my own question. This code works:

            public void Post([FromBody]string message)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(a => SendToDeviceMessage(message));
            }

            // This thread procedure performs the task.
            static void SendToDeviceMessage(Object messageObject)
            {
                string message = (string)messageObject;
                serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
                var commandMessage = new Message(Encoding.ASCII.GetBytes(message));
                serviceClient.SendAsync("HemsedalController", commandMessage).Wait();
            }

    Thursday, August 25, 2016 7:46 AM