使用资源提供程序 REST API 创建 IoT 中心 (.NET)Create an IoT hub using the resource provider REST API (.NET)

可以通过编程方式使用 IoT 中心资源提供程序 REST API 创建和管理 Azure IoT 中心。You can use the IoT Hub resource provider REST API to create and manage Azure IoT hubs programmatically. 本教程介绍如何使用 IoT 中心资源提供程序 REST API 通过 C# 程序创建 IoT 中心。This tutorial shows you how to use the IoT Hub resource provider REST API to create an IoT hub from a C# program.

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

要完成本教程,需要以下各项:To complete this tutorial, you need the following:

  • Visual Studio。Visual Studio.

  • 有效的 Azure 帐户。An active Azure account.
    如果没有帐户,只需花费几分钟就能创建一个帐户If you don't have an account, you can create a account in just a couple of minutes.

  • Azure PowerShell 1.0 或更高版本。Azure PowerShell 1.0 or later.

准备对 Azure Resource Manager 请求进行身份验证Prepare to authenticate Azure Resource Manager requests

必须使用 Azure Resource Manager 配合 Azure Active Directory (AD) 来验证所有针对资源执行的操作。You must authenticate all the operations that you perform on resources using the Azure Resource Manager with Azure Active Directory (AD). 最简单的配置方式是使用 PowerShell 或 Azure CLI。The easiest way to configure this is to use PowerShell or Azure CLI.

在继续之前,请安装 Azure PowerShell cmdletInstall the Azure PowerShell cmdlets before you continue.

以下步骤说明如何使用 PowerShell 设置 AD 应用程序的密码身份验证。The following steps show how to set up password authentication for an AD application using PowerShell. 可以在标准 PowerShell 会话中运行这些命令。You can run these commands in a standard PowerShell session.

  1. 使用以下命令登录到 Azure 订阅:Sign in to your Azure subscription using the following command:

    Connect-AzureRmAccount -Environment AzureChinaCloud
    
  2. 如果有多个 Azure 订阅,则访问 Azure 即有权访问与凭据关联的所有 Azure 订阅。If you have multiple Azure subscriptions, signing in to Azure grants you access to all the Azure subscriptions associated with your credentials. 使用以下命令,列出可供使用的 Azure 订阅:Use the following command to list the Azure subscriptions available for you to use:

    Get-AzureRMSubscription
    

    使用以下命令,选择想要用于运行命令以管理 IoT 中心的订阅。Use the following command to select subscription that you want to use to run the commands to manage your IoT hub. 可使用上一命令输出中的订阅名称或 ID:You can use either the subscription name or ID from the output of the previous command:

    Select-AzureRMSubscription `
        -SubscriptionName "{your subscription name}"
    
  3. 记下 TenantIdSubscriptionIdMake a note of your TenantId and SubscriptionId. 稍后会需要它们。You need them later.

  4. 使用以下命令并替换占位符,以创建新的 Azure Active Directory 应用程序:Create a new Azure Active Directory application using the following command, replacing the place holders:

    • {Display name}:应用程序的显示名称,例如 MySampleApp{Display name}: a display name for your application such as MySampleApp

    • {Home page URL}: 应用主页的 URL,例如 http://mysampleapp/home。{Home page URL}: the URL of the home page of your app such as http://mysampleapp/home. 此 URL 不需要指向实际的应用程序。This URL does not need to point to a real application.

    • {Application identifier}: 唯一的标识符,例如 http://mysampleapp{Application identifier}: A unique identifier such as http://mysampleapp. 此 URL 不需要指向实际的应用程序。This URL does not need to point to a real application.

    • {Password}: 用于向应用进行身份验证的密码。{Password}: A password that you use to authenticate with your app.

      $SecurePassword=ConvertTo-SecureString {password} �asplaintext �force
      New-AzureRmADApplication -DisplayName {Display name} -HomePage {Home page URL} -IdentifierUris {Application identifier} -Password $SecurePassword
      
  5. 请记下创建的应用程序的 ApplicationIdMake a note of the ApplicationId of the application you created. 稍后会需要它。You need this later.

  6. 使用以下命令(将 {MyApplicationId} 替换为上一步骤中的 ApplicationId)创建新的服务主体:Create a new service principal using the following command, replacing {MyApplicationId} with the ApplicationId from the previous step:

    New-AzureRmADServicePrincipal -ApplicationId {MyApplicationId}
    
  7. 使用以下命令(将 {MyApplicationId} 替换为 ApplicationId)设置角色分配。Set up a role assignment using the following command, replacing {MyApplicationId} with your ApplicationId.

    New-AzureRmRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName {MyApplicationId}
    

现在,已创建可从自定义 C# 应用程序进行身份验证的 Azure AD 应用程序。You have now finished creating the Azure AD application that enables you to authenticate from your custom C# application. 在本教程的后续内容中,需要用到以下值:You need the following values later in this tutorial:

  • TenantIdTenantId
  • SubscriptionIdSubscriptionId
  • ApplicationIdApplicationId
  • 密码Password

准备 Visual Studio 项目Prepare your Visual Studio project

  1. 在 Visual Studio 中,使用“控制台应用(.NET Framework)” 项目模板创建 Visual C# Windows 经典桌面项目。In Visual Studio, create a Visual C# Windows Classic Desktop project using the Console App (.NET Framework) project template. 将该项目命名为 CreateIoTHubRESTName the project CreateIoTHubREST.

  2. 在解决方案资源管理器中右键单击项目,然后单击“管理 NuGet 包”。In Solution Explorer, right-click on your project and then click Manage NuGet Packages.

  3. 在 NuGet 包管理器中,选中“包括预发行版”,并在“浏览”页上搜索 Microsoft.Azure.Management.ResourceManagerIn NuGet Package Manager, check Include prerelease, and on the Browse page search for Microsoft.Azure.Management.ResourceManager. 选择该包,单击“安装” ,在“审阅更改” 中单击“确定” ,并单击“我接受” 以接受许可证。Select the package, click Install, in Review Changes click OK, then click I Accept to accept the licenses.

  4. 在 NuGet 包管理器中,搜索 Microsoft.IdentityModel.Clients.ActiveDirectoryIn NuGet Package Manager, search for Microsoft.IdentityModel.Clients.ActiveDirectory. 单击“安装”,在“审阅更改”中单击“确定”,并单击“我接受”以接受许可证。Click Install, in Review Changes click OK, then click I Accept to accept the license.

  5. 在 Program.cs 中,将现有 using 语句替换为以下代码:In Program.cs, replace the existing using statements with the following code:

    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using Microsoft.Azure.Management.ResourceManager;
    using Microsoft.Azure.Management.ResourceManager.Models;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using System.Linq;
    using System.Threading;
    
  6. 在 Program.cs 中,将占位符值替换为以下静态变量。In Program.cs, add the following static variables replacing the placeholder values. 在本教程前面的介绍中,已记下 ApplicationIdSubscriptionIdTenantIdPasswordYou made a note of ApplicationId, SubscriptionId, TenantId, and Password earlier in this tutorial. 资源组名称 是创建 IoT 中心时要使用的资源组名称。Resource group name is the name of the resource group you use when you create the IoT hub. 可以使用现有的资源组或新资源组。You can use a pre-existing or a new resource group. “IoT 中心名称” 是你创建的 IoT 中心的名称,例如“MyIoTHub” 。IoT Hub name is the name of the IoT Hub you create, such as MyIoTHub. IoT 中心的名称必须是全局唯一的。The name of your IoT hub must be globally unique. 部署名称是部署的名称,例如 Deployment_01Deployment name is a name for the deployment, such as Deployment_01.

    static string applicationId = "{Your ApplicationId}";
    static string subscriptionId = "{Your SubscriptionId}";
    static string tenantId = "{Your TenantId}";
    static string password = "{Your application Password}";
    
    static string rgName = "{Resource group name}";
    static string iotHubName = "{IoT Hub name including your initials}";
    

    重要

    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 资源管理器令牌Obtain an Azure Resource Manager token

Azure Active Directory 必须使用 Azure Resource Manager 来验证所有针对资源执行的任务。Azure Active Directory must authenticate all the tasks that you perform on resources using the Azure Resource Manager. 此处显示的示例使用密码身份验证。有关其他方法,请参阅对 Azure 资源管理器请求进行身份验证The example shown here uses password authentication, for other approaches see Authenticating Azure Resource Manager requests.

  1. 将以下代码添加到 Program.cs 中的 Main 方法,以使用应用程序 ID 和密码从 Azure AD 中检索令牌。Add the following code to the Main method in Program.cs to retrieve a token from Azure AD using the application id and password.

    var authContext = new AuthenticationContext(string.Format  
      ("https://login.microsoftonline.com/{0}", tenantId));
    var credential = new ClientCredential(applicationId, password);
    AuthenticationResult token = authContext.AcquireTokenAsync
      ("https://management.core.windows.net/", credential).Result;
    
    if (token == null)
    {
      Console.WriteLine("Failed to obtain the token");
      return;
    }
    
  2. 创建一个 ResourceManagementClient 对象,该对象通过在 Main 方法的末尾添加以下代码来使用令牌:Create a ResourceManagementClient object that uses the token by adding the following code to the end of the Main method:

    var creds = new TokenCredentials(token.AccessToken);
    var client = new ResourceManagementClient(creds);
    client.SubscriptionId = subscriptionId;
    
  3. 创建或获取对你使用的资源组的引用:Create, or obtain a reference to, the resource group you are using:

    var rgResponse = client.ResourceGroups.CreateOrUpdate(rgName,
        new ResourceGroup("East US"));
    if (rgResponse.Properties.ProvisioningState != "Succeeded")
    {
      Console.WriteLine("Problem creating resource group");
      return;
    }
    

使用资源提供程序 REST API 创建 IoT 中心Use the resource provider REST API to create an IoT hub

在资源组中使用 IoT 中心资源提供程序 REST API 创建 IoT 中心。Use the IoT Hub resource provider REST API to create an IoT hub in your resource group. 还可以使用资源提供程序 REST API 更改现有的 IoT 中心。You can also use the resource provider REST API to make changes to an existing IoT hub.

  1. 将以下方法添加到 Program.cs:Add the following method to Program.cs:

    static void CreateIoTHub(string token)
    {
    
    }
    
  2. 将以下代码添加到 CreateIoTHub 方法中。Add the following code to the CreateIoTHub method. 该代码使用标头中的身份验证令牌创建 HttpClient 对象:This code creates an HttpClient object with the authentication token in the headers:

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    
  3. 将以下代码添加到 CreateIoTHub 方法中。Add the following code to the CreateIoTHub method. 此代码描述要创建的 IoT 中心,并生成 JSON 表示形式。This code describes the IoT hub to create and generates a JSON representation. 有关支持 IoT 中心的位置的最新列表,请参阅 Azure 状态For the current list of locations that support IoT Hub see Azure Status:

    var description = new
    {
      name = iotHubName,
      location = "China East",
      sku = new
      {
        name = "S1",
        tier = "Standard",
        capacity = 1
      }
    };
    
    var json = JsonConvert.SerializeObject(description, Formatting.Indented);
    
  4. 将以下代码添加到 CreateIoTHub 方法中。Add the following code to the CreateIoTHub method. 使用此代码将 REST 请求提交到 Azure。This code submits the REST request to Azure. 然后该代码会检查响应,并检索可用于监视部署任务状态的 URL:The code then checks the response and retrieves the URL you can use to monitor the state of the deployment task:

    var content = new StringContent(JsonConvert.SerializeObject(description), Encoding.UTF8, "application/json");
    var requestUri = string.Format("https://management.chinacloudapi.cn/subscriptions/{0}/resourcegroups/{1}/providers/Microsoft.devices/IotHubs/{2}?api-version=2016-02-03", subscriptionId, rgName, iotHubName);
    var result = client.PutAsync(requestUri, content).Result;
    
    if (!result.IsSuccessStatusCode)
    {
      Console.WriteLine("Failed {0}", result.Content.ReadAsStringAsync().Result);
      return;
    }
    
    var asyncStatusUri = result.Headers.GetValues("Azure-AsyncOperation").First();
    
  5. 将以下代码添加到 CreateIoTHub 方法的末尾。Add the following code to the end of the CreateIoTHub method. 该代码使用上一个步骤中检索的 asyncStatusUri 地址来等待部署完成:This code uses the asyncStatusUri address retrieved in the previous step to wait for the deployment to complete:

    string body;
    do
    {
      Thread.Sleep(10000);
      HttpResponseMessage deploymentstatus = client.GetAsync(asyncStatusUri).Result;
      body = deploymentstatus.Content.ReadAsStringAsync().Result;
    } while (body == "{\"status\":\"Running\"}");
    
  6. 将以下代码添加到 CreateIoTHub 方法的末尾。Add the following code to the end of the CreateIoTHub method. 此代码检索创建的 IoT 中心的键,并将其打印到控制台:This code retrieves the keys of the IoT hub you created and prints them to the console:

    var listKeysUri = string.Format("https://management.azure.cn/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Devices/IotHubs/{2}/IoTHubKeys/listkeys?api-version=2016-02-03", subscriptionId, rgName, iotHubName);
    var keysresults = client.PostAsync(listKeysUri, null).Result;
    
    Console.WriteLine("Keys: {0}", keysresults.Content.ReadAsStringAsync().Result);
    

完成并运行应用程序Complete and run the application

现在,可以调用 CreateIoTHub 方法来完成应用程序,然后生成并运行该应用程序。You can now complete the application by calling the CreateIoTHub method before you build and run it.

  1. 将以下代码添加到 Main 方法末尾:Add the following code to the end of the Main method:

    CreateIoTHub(token.AccessToken);
    Console.ReadLine();
    
  2. 单击“生成”,并单击“生成解决方案”。Click Build and then Build Solution. 更正所有错误。Correct any errors.

  3. 单击“调试”,并单击“开始调试”以运行应用程序。Click Debug and then Start Debugging to run the application. 运行部署可能需要几分钟时间。It may take several minutes for the deployment to run.

  4. 若要验证应用程序是否添加了新的 IoT 中心,请访问 Azure 门户并查看资源列表。To verify that your application added the new IoT hub, visit the Azure portal and view your list of resources. 另外,也可以使用 Get-AzResource PowerShell cmdlet。Alternatively, use the Get-AzResource PowerShell cmdlet.

备注

本示例应用程序将添加用于对你计费的 S1 标准 IoT 中心。This example application adds an S1 Standard IoT Hub for which you are billed. 在完成任务后,可以通过 Azure 门户或者使用 Remove-AzResource PowerShell cmdlet 删除该 IoT 中心。When you are finished, you can delete the IoT hub through the Azure portal or by using the Remove-AzResource PowerShell cmdlet when you are finished.

后续步骤Next steps

现在,已使用资源提供程序 REST API 部署了一个 IoT 中心,接下来可以进一步进行探索:Now you have deployed an IoT hub using the resource provider REST API, you may want to explore further:

若要详细了解如何开发 IoT 中心,请参阅以下文章:To learn more about developing for IoT Hub, see the following articles:

若要进一步探索 IoT 中心的功能,请参阅:To further explore the capabilities of IoT Hub, see: