设备管理入门 (.NET)Get started with device management (.NET)

后端应用可以使用 Azure IoT 中心基元(例如设备孪生直接方法)远程启动和监视设备上的设备管理操作。Back-end apps can use Azure IoT Hub primitives, such as device twin and direct methods, to remotely start and monitor device management actions on devices. 本教程说明后端应用和设备应用如何协同工作,以便使用 IoT 中心发起远程设备重启操作并对其进行监视。This tutorial shows you how a back-end app and a device app can work together to initiate and monitor a remote device reboot using IoT Hub.


本文介绍的功能仅在 IoT 中心的标准层中可用。The features described in this article are available only in the standard tier of IoT Hub. 有关基本和标准/免费 IoT 中心层的详细信息,请参阅选择合适的 IoT 中心层For more information about the basic and standard/free IoT Hub tiers, see Choose the right IoT Hub tier.

使用直接方法可从云中的后端应用启动设备管理操作(例如重新启动、恢复出厂设置以及固件更新)。Use a direct method to initiate device management actions (such as reboot, factory reset, and firmware update) from a back-end app in the cloud. 设备负责以下操作:The device is responsible for:

  • 处理从 IoT 中心发送的方法请求。Handling the method request sent from IoT Hub.
  • 在设备上启动相应的设备特定操作。Initiating the corresponding device-specific action on the device.
  • 通过向 IoT 中心 报告的属性,提供状态更新。Providing status updates through reported properties to IoT Hub.

可以使用云中的后端应用运行设备孪生查询,以报告设备管理操作的进度。You can use a back-end app in the cloud to run device twin queries to report on the progress of your device management actions.

本教程演示如何:This tutorial shows you how to:

  • 使用 Azure 门户创建 IoT 中心,以及如何在 IoT 中心创建设备标识。Use the Azure portal to create an IoT Hub and create a device identity in your IoT hub.
  • 创建包含重新启动该设备的直接方法的模拟设备应用。Create a simulated device app that contains a direct method that reboots that device. 直接方法是从云中调用的。Direct methods are invoked from the cloud.
  • 创建一个 .NET 控制台应用,其通过 IoT 中心在模拟设备应用上调用重新启动直接方法。Create a .NET console app that calls the reboot direct method in the simulated device app through your IoT hub.

在本教程结束时,会获得两个 .NET 控制台应用:At the end of this tutorial, you have two .NET console apps:

  • SimulateManagedDevice。SimulateManagedDevice. 此应用使用先前创建的设备标识连接到 IoT 中心,接收重新启动直接方法,模拟物理重新启动,并报告上次重新启动的时间。This app connects to your IoT hub with the device identity created earlier, receives a reboot direct method, simulates a physical reboot, and reports the time for the last reboot.

  • TriggerReboot。TriggerReboot. 此应用在模拟设备应用中调用直接方法、显示响应以及显示更新的报告属性。This app calls a direct method in the simulated device app, displays the response, and displays the updated reported properties.


  • Visual Studio。Visual Studio.
  • 有效的 Azure 帐户。An active Azure account. (如果没有帐户,只需几分钟即可创建一个试用帐户。)(If you don't have an account, you can create a trial account in just a couple of minutes.)
  • 确保已在防火墙中打开端口 8883。Make sure that port 8883 is open in your firewall. 本文中的设备示例使用 MQTT 协议,该协议通过端口 8883 进行通信。The device sample in this article uses MQTT protocol, which communicates over port 8883. 在某些公司和教育网络环境中,此端口可能被阻止。This port may be blocked in some corporate and educational network environments. 有关解决此问题的更多信息和方法,请参阅连接到 IoT 中心(MQTT)For more information and ways to work around this issue, see Connecting to IoT Hub (MQTT).

创建 IoT 中心Create an IoT hub

此部分介绍如何使用 Azure 门户创建 IoT 中心。This section describes how to create an IoT hub using the Azure portal.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 从 Azure 主页中选择“+ 创建资源”按钮,然后在“搜索市场”字段中输入“IoT 中心”。 From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.

  3. 在搜索结果中选择“IoT 中心”,然后选择“创建” 。Select IoT Hub from the search results, and then select Create.

  4. 在“基本信息”选项卡上,按如下所示填写字段: On the Basics tab, complete the fields as follows:

    • 订阅:选择要用于中心的订阅。Subscription: Select the subscription to use for your hub.

    • 资源组:选择一个资源组或新建一个资源组。Resource Group: Select a resource group or create a new one. 若要新建资源组,请选择“新建”并填写要使用的名称。 To create a new one, select Create new and fill in the name you want to use. 若要使用现有的资源组,请选择它。To use an existing resource group, select that resource group. 有关详细信息,请参阅管理 Azure 资源管理器资源组For more information, see Manage Azure Resource Manager resource groups.

    • 区域:选择中心所在的区域。Region: Select the region in which you want your hub to be located. 选择最靠近你的位置。Select the location closest to you.

    • IoT 中心名称:输入中心的名称。IoT Hub Name: Enter a name for your hub. 此名称必须全局唯一。This name must be globally unique. 如果输入的名称可用,会显示一个绿色复选标记。If the name you enter is available, a green check mark appears.


    IoT 中心将公开为 DNS 终结点,因此,命名时请务必避免包含任何敏感信息。The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it.

    在 Azure 门户中创建中心

  5. 在完成时选择“下一步: 大小和规模”,以继续创建中心。Select Next: Size and scale to continue creating your hub.

    使用 Azure 门户为新的中心设置大小和规模

    可在此处接受默认设置。You can accept the default settings here. 如果需要,可以修改以下任何字段:If desired, you can modify any of the following fields:

    • 定价和缩放层:选择的层。Pricing and scale tier: Your selected tier. 可以根据你需要的功能数以及每天通过解决方案发送的消息数从多个层级中进行选择。You can choose from several tiers, depending on how many features you want and how many messages you send through your solution per day. 免费层适用于测试和评估。The free tier is intended for testing and evaluation. 允许 500 台设备连接到中心,每天最多可传输 8,000 条消息。It allows 500 devices to be connected to the hub and up to 8,000 messages per day. 每个 Azure 订阅可以在免费层中创建一个 IoT 中心。Each Azure subscription can create one IoT hub in the free tier.

      如果正在完成 IoT 中心设备流的快速入门,请选择免费层。If you are working through a Quickstart for IoT Hub device streams, select the free tier.

    • IoT 中心单元:每个单位每日允许的消息数取决于中心的定价层。IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. 例如,如果希望中心支持 700,000 条消息引入,请选择两个 S1 层单位。For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. 有关其他层选项的详细信息,请参阅选择合适的 IoT 中心层For details about the other tier options, see Choosing the right IoT Hub tier.

    • 高级设置 > 设备到云的分区:此属性将设备到云消息与这些消息的同步读取器数目相关联。Advanced Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. 大多数中心只需要 4 个分区。Most hubs need only four partitions.

  6. 在完成时选择“下一步: 标记”继续到下一屏幕。Select Next: Tags to continue to the next screen.

    标记是名称/值对。Tags are name/value pairs. 可以为多个资源和资源组分配相同的标记,以便对资源进行分类并合并计费。You can assign the same tag to multiple resources and resource groups to categorize resources and consolidate billing. 有关详细信息,请参阅使用标记来组织 Azure 资源for more information, see Use tags to organize your Azure resources.

    使用 Azure 门户为新的中心设置大小和规模

  7. 在完成时选择“下一步: 查看+创建”可查看选择。Select Next: Review + create to review your choices. 你会看到类似于此屏幕的内容,但其中包含创建中心时选择的值。You see something similar to this screen, but with the values you selected when creating the hub.


  8. 选择“创建”以创建新的中心 。Select Create to create your new hub. 创建中心需要几分钟时间。Creating the hub takes a few minutes.

在 IoT 中心内注册新设备Register a new device in the IoT hub

本部分在 IoT 中心的标识注册表中创建设备标识。In this section, you create a device identity in the identity registry in your IoT hub. 除非设备在标识注册表中具有条目,否则设备无法连接到中心。A device cannot connect to a hub unless it has an entry in the identity registry. 有关详细信息,请参阅 IoT 中心开发人员指南For more information, see the IoT Hub developer guide.

  1. 在 IoT 中心导航菜单中,打开“IoT 设备” ,然后选择“新建” 以在 IoT 中心中添加设备。In your IoT hub navigation menu, open IoT Devices, then select New to add a device in your IoT hub.


  2. 在“创建设备” 中,为新设备提供名称(例如 myDeviceId),然后选择“保存” 。In Create a device, provide a name for your new device, such as myDeviceId, and select Save. 此操作会为 IoT 中心创建设备标识。This action creates a device identity for your IoT hub.



    收集的日志中可能会显示设备 ID 用于客户支持和故障排除,因此,在为日志命名时,请务必避免包含任何敏感信息。The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

  3. 创建设备后,在“IoT 设备”窗格的列表中打开该设备 。After the device is created, open the device from the list in the IoT devices pane. 复制主连接字符串以便稍后使用。Copy the Primary Connection String to use later.



IoT 中心标识注册表只存储设备标识,以启用对 IoT 中心的安全访问。The IoT Hub identity registry only stores device identities to enable secure access to the IoT hub. 它存储设备 ID 和密钥用作安全凭据,以及可用于禁用单个设备访问的启用/禁用标志。It stores device IDs and keys to use as security credentials, and an enabled/disabled flag that you can use to disable access for an individual device. 如果应用程序需要存储其他特定于设备的元数据,则应使用特定于应用程序的存储。If your application needs to store other device-specific metadata, it should use an application-specific store. 有关详细信息,请参阅 IoT 中心开发人员指南For more information, see IoT Hub developer guide.

获取 IoT 中心连接字符串Get the IoT hub connection string

在本文中,你将创建一个在设备上调用直接方法的后端服务。In this article, you create a backend service that invokes a direct method on a device. 若要通过 IoT 中心在设备上调用直接方法,服务需要“服务连接” 权限。To invoke a direct method on a device through IoT Hub, your service needs the service connect permission. 默认情况下,每个 IoT 中心都使用名为 service 的共享访问策略创建,该策略授予此权限。By default, every IoT Hub is created with a shared access policy named service that grants this permission.

若要获取 service 策略的 IoT 中心连接字符串,请执行以下步骤:To get the IoT Hub connection string for the service policy, follow these steps:

  1. Azure 门户中,选择“资源组” 。In the Azure portal, select Resource groups. 选择中心所在的资源组,然后从资源列表中选择中心。Select the resource group where your hub is located, and then select your hub from the list of resources.

  2. 在 IoT 中心的左侧窗格中,选择“共享访问策略” 。On the left-side pane of your IoT hub, select Shared access policies.

  3. 从策略列表中选择“service” 策略。From the list of policies, select the service policy.

  4. 在“共享访问密钥” 下,选择“连接字符串 - 主密钥” 所对应的“复制”图标并保存该值。Under Shared access keys, select the copy icon for the Connection string -- primary key and save the value.


有关 IoT 中心共享访问策略和权限的详细信息,请参阅访问控制和权限For more information about IoT Hub shared access policies and permissions, see Access control and permissions.

使用直接方法在设备上触发远程重新启动Trigger a remote reboot on the device using a direct method

在本部分中,会创建一个 .NET 控制台应用(使用 C#)以使用直接方法在设备上启动远程重新启动。In this section, you create a .NET console app, using C#, that initiates a remote reboot on a device using a direct method. 该应用使用设备孪生查询来搜索该设备的上次重新启动时间。The app uses device twin queries to discover the last reboot time for that device.

  1. 在 Visual Studio 中选择“创建新项目”。In Visual Studio, select Create a new project.

  2. 在“创建新项目”中,找到并选择“控制台应用(.NET Framework)”项目模板,然后选择“下一步”。 In Create a new project, find and select the Console App (.NET Framework) project template, and then select Next.

  3. 在“配置新项目”,将项目命名为 TriggerReboot,然后选择 .NET Framework 版本 4.5.1 或更高版本。In Configure your new project, name the project TriggerReboot, and select .NET Framework version 4.5.1 or later. 选择“创建”。Select Create.

    新的 Visual C# Windows 经典桌面项目

  4. 在“解决方案资源管理器”中,右键单击“TriggerReboot”项目,然后选择“管理 NuGet 程序包” 。In Solution Explorer, right-click the TriggerReboot project, and then select Manage NuGet Packages.

  5. 选择“浏览”,然后搜索并选择“Microsoft.Azure.Devices”。Select Browse, then search for and select Microsoft.Azure.Devices. 选择“安装”以安装“Microsoft.Azure.Devices”包。Select Install to install the Microsoft.Azure.Devices package.

    “NuGet 包管理器”窗口

    此步骤将下载、安装 Azure IoT 服务 SDK NuGet 包及其依赖项并添加对其的引用。This step downloads, installs, and adds a reference to the Azure IoT service SDK NuGet package and its dependencies.

  6. 在 Program.cs 文件顶部添加以下 using 语句:Add the following using statements at the top of the Program.cs file:

    using Microsoft.Azure.Devices;
    using Microsoft.Azure.Devices.Shared;
  7. 将以下字段添加到 Program 类。Add the following fields to the Program class. {iot hub connection string} 占位符值替换为以前在获取 IoT 中心连接字符串中复制的 IoT 中心连接字符串。Replace the {iot hub connection string} placeholder value with the IoT Hub connection string you copied previously in Get the IoT hub connection string.

    static RegistryManager registryManager;
    static string connString = "{iot hub connection string}";
    static ServiceClient client;
    static string targetDevice = "myDeviceId";
  8. 将以下方法添加到 Program 类。Add the following method to the Program class. 此代码为重新启动的设备获取设备克隆,并输出报告的属性。This code gets the device twin for the rebooting device and outputs the reported properties.

    public static async Task QueryTwinRebootReported()
        Twin twin = await registryManager.GetTwinAsync(targetDevice);
  9. 将以下方法添加到 Program 类。Add the following method to the Program class. 此代码使用直接方法在设备上启动重启。This code initiates the reboot on the device using a direct method.

    public static async Task StartReboot()
        client = ServiceClient.CreateFromConnectionString(connString);
        CloudToDeviceMethod method = new CloudToDeviceMethod("reboot");
        method.ResponseTimeout = TimeSpan.FromSeconds(30);
        CloudToDeviceMethodResult result = await 
          client.InvokeDeviceMethodAsync(targetDevice, method);
        Console.WriteLine("Invoked firmware update on device.");
  10. 最后,在 Main 方法中添加以下行:Finally, add the following lines to the Main method:

    registryManager = RegistryManager.CreateFromConnectionString(connString);
    Console.WriteLine("Press ENTER to exit.");
  11. 选择“生成” > “生成解决方案”。Select Build > Build Solution.


本教程仅针对设备的报告属性执行单个查询。This tutorial performs only a single query for the device's reported properties. 在生产代码中,我们建议通过轮询来检测报告属性是否更改。In production code, we recommend polling to detect changes in the reported properties.

创建模拟设备应用程序Create a simulated device app

本部分的操作:In this section, you:

  • 创建一个 .NET 控制台应用,用于响应通过云调用的直接方法。Create a .NET console app that responds to a direct method called by the cloud.

  • 触发模拟设备重新启动。Trigger a simulated device reboot.

  • 通过报告的属性,设备孪生查询可标识设备及设备上次重新启动的时间。Use the reported properties to enable device twin queries to identify devices and when they were last rebooted.

若要创建模拟设备应用,请执行以下步骤:To create the simulated device app, follow these steps:

  1. 在 Visual Studio 中,在已创建的 TriggerReboot 解决方案中,选择“文件” > “新建” > “项目”。In Visual Studio, in the TriggerReboot solution you already created, select File > New > Project. 在“创建新项目”中,找到并选择“控制台应用(.NET Framework)”项目模板,然后选择“下一步”。 In Create a new project, find and select the Console App (.NET Framework) project template, and then select Next.

  2. 在“配置新项目”,将项目命名为 SimulateManagedDevice,对于“解决方案”,选择“添加到解决方案”。In Configure your new project, name the project SimulateManagedDevice, and for Solution, select Add to solution. 选择“创建”。Select Create.


  3. 在“解决方案资源管理器”中,右键单击新的“SimulateManagedDevice”项目,然后选择“管理 NuGet 程序包”。In Solution Explorer, right-click the new SimulateManagedDevice project, and then select Manage NuGet Packages.

  4. 选择“浏览”,然后搜索并选择“Microsoft.Azure.Devices.Client”。Select Browse, then search for and select Microsoft.Azure.Devices.Client. 选择“安装”。Select Install.

    “NuGet 包管理器”窗口客户端应用

    此步骤将下载、安装 Azure IoT 设备 SDK NuGet 包及其依赖项并添加对其的引用。This step downloads, installs, and adds a reference to the Azure IoT device SDK NuGet package and its dependencies.

  5. 在 Program.cs 文件顶部添加以下 using 语句:Add the following using statements at the top of the Program.cs file:

    using Microsoft.Azure.Devices.Client;
    using Microsoft.Azure.Devices.Shared;
  6. 将以下字段添加到 Program 类。Add the following fields to the Program class. {device connection string} 占位符值替换为以前在在 IoT 中心内注册新设备中记下的设备连接字符串。Replace the {device connection string} placeholder value with the device connection string that you noted previously in Register a new device in the IoT hub.

    static string DeviceConnectionString = "{device connection string}";
    static DeviceClient Client = null;
  7. 添加以下函数,实现设备上的直接方法:Add the following to implement the direct method on the device:

    static Task<MethodResponse> onReboot(MethodRequest methodRequest, object userContext)
        // In a production device, you would trigger a reboot 
        //   scheduled to start after this method returns.
        // For this sample, we simulate the reboot by writing to the console
        //   and updating the reported properties.
            // Update device twin with reboot time. 
            TwinCollection reportedProperties, reboot, lastReboot;
            lastReboot = new TwinCollection();
            reboot = new TwinCollection();
            reportedProperties = new TwinCollection();
            lastReboot["lastReboot"] = DateTime.Now;
            reboot["reboot"] = lastReboot;
            reportedProperties["iothubDM"] = reboot;
        catch (Exception ex)
            Console.WriteLine("Error in sample: {0}", ex.Message);
        string result = @"{""result"":""Reboot started.""}";
        return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
  8. 最后,将以下代码添加到 Main 方法,打开与 IoT 中心的连接并初始化方法侦听器:Finally, add the following code to the Main method to open the connection to your IoT hub and initialize the method listener:

        Console.WriteLine("Connecting to hub");
        Client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, 
        // setup callback for "reboot" method
        Client.SetMethodHandlerAsync("reboot", onReboot, null).Wait();
        Console.WriteLine("Waiting for reboot method\n Press enter to exit.");
        // as a good practice, remove the "reboot" handler
        Client.SetMethodHandlerAsync("reboot", null, null).Wait();
    catch (Exception ex)
        Console.WriteLine("Error in sample: {0}", ex.Message);
  9. 在解决方案资源管理器中,右键单击解决方案,然后选择“设置启动项目”。In Solution Explorer, right-click your solution, and then select Set StartUp Projects.

  10. 在“通用属性” > “启动项目”中,选择“单启动项目”,然后选择“SimulateManagedDevice”项目。For Common Properties > Startup Project, Select Single startup project, and then select the SimulateManagedDevice project. 选择“确定”保存更改。Select OK to save your changes.

  11. 选择“生成” > “生成解决方案” 。Select Build > Build Solution.


为简单起见,本教程不实现任何重试策略。To keep things simple, this tutorial does not implement any retry policy. 在生产代码中,应该按暂时性故障处理中所述实施重试策略(例如指数退避)。In production code, you should implement retry policies (such as an exponential backoff), as suggested in Transient Fault Handling.

运行应用Run the apps

现在可以运行应用了。You are now ready to run the apps.

  1. 若要运行 .NET 设备应用 SimulateManagedDevice,请在解决方案资源管理器中,右键单击“SimulateManagedDevice”项目,选择“调试”,然后选择“启动新实例”。To run the .NET device app SimulateManagedDevice, in Solution Explorer, right-click the SimulateManagedDevice project, select Debug, and then select Start new instance. 应用应开始侦听来自 IoT 中心的方法调用。The app should start listening for method calls from your IoT hub.

  2. 在设备已连接并等待方法调用之后,右键单击“TriggerReboot”项目,选择“调试”,然后选择“启动新实例”。After that the device is connected and waiting for method invocations, right-click the TriggerReboot project, select Debug, and then select Start new instance.

    应会看到“正在重新启动!”You should see "Rebooting!" SimulatedManagedDevice 控制台中写入,设备的报告属性(包括上次重新启动时间)在 TriggerReboot 控制台中写入。written in the SimulatedManagedDevice console and the reported properties of the device, which include the last reboot time, written in the TriggerReboot console.


自定义和扩展设备管理操作Customize and extend the device management actions

IoT 解决方案可扩展已定义的设备管理模式集,或通过使用设备孪生和云到设备方法基元启用自定义模式。Your IoT solutions can expand the defined set of device management patterns or enable custom patterns by using the device twin and cloud-to-device method primitives. 设备管理操作的其他示例包括恢复出厂设置、固件更新、软件更新、电源管理、网络和连接管理以及数据加密。Other examples of device management actions include factory reset, firmware update, software update, power management, network and connectivity management, and data encryption.

设备维护时段Device maintenance windows

通常情况下,将设备配置为在某一时间执行操作,以最大程度减少中断和停机时间。Typically, you configure devices to perform actions at a time that minimizes interruptions and downtime. 设备维护时段是一种常用模式,用于定义设备应更新其配置的时间。Device maintenance windows are a commonly used pattern to define the time when a device should update its configuration. 后端解决方案使用设备孪生所需属性在设备上定义并激活策略,以启用维护时段。Your back-end solutions can use the desired properties of the device twin to define and activate a policy on your device that enables a maintenance window. 当设备收到维护时段策略时,它可以使用设备孪生报告属性报告策略状态。When a device receives the maintenance window policy, it can use the reported property of the device twin to report the status of the policy. 然后,后端应用可以使用设备孪生查询来证明设备和每个策略的符合性。The back-end app can then use device twin queries to attest to compliance of devices and each policy.

后续步骤Next steps

本教程使用直接方法触发设备上的远程重新启动。In this tutorial, you used a direct method to trigger a remote reboot on a device. 使用报告属性报告设备上次重新启动时间,并查询设备孪生从云中发现设备上次重新启动时间。You used the reported properties to report the last reboot time from the device, and queried the device twin to discover the last reboot time of the device from the cloud.

若要继续完成 IoT 中心和设备管理模式(如远程无线固件更新)的入门内容,请参阅如何更新固件To continue getting started with IoT Hub and device management patterns such as remote over the air firmware update, see How to do a firmware update.

若要了解如何扩展 IoT 解决方案并在多个设备上计划方法调用,请参阅计划和广播作业To learn how to extend your IoT solution and schedule method calls on multiple devices, see Schedule and broadcast jobs.