Hi @Hocker, Cary Greetings! Welcome to Microsoft Q&A forum. Thank you for posting this question here.
Here is an Azure function sample code to achieve what you are looking for
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.Devices;
namespace Raj.ServiceClient
{
public static class IoTServiceClient
{
private static RegistryManager _registryManager;
[FunctionName("IoTServiceClient")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
if (_registryManager == null)
{
// Connection string for the IoT Hub
string connectionString = "<IoTHubOwnerConnectionString>";
// Create a new instance of RegistryManager using the IoT Hub connection string
_registryManager = RegistryManager.CreateFromConnectionString(connectionString);
}
string deviceId = req.Query["deviceId"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
deviceId = deviceId ?? data?.name;
// Check if the device exists
Device device = await _registryManager.GetDeviceAsync(deviceId);
if (device == null)
{
// Device does not exist
Console.WriteLine($"Device with ID {deviceId} does not exist.");
}
else
{
// Device exists
Console.WriteLine($"Device with ID {deviceId} exists.");
}
string responseMessage = string.IsNullOrEmpty(deviceId)
? $"Hello, {deviceId} does not exists."
: $"Hello, {deviceId} exists.";
return new OkObjectResult(responseMessage);
}
}
}
I have tested this function locally and you can pass the device ID as a query parameter to invoke the HTPP trigger function as follows http://localhost:7071/api/IoTServiceClient?deviceid=TestDevice4. Please find the below snippet from the function execution stack.
Hope this helps. Please let us know if you have any additional questions or need further assistance.
If the response helped, please do click Accept Answer and Yes. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.