在 Azure Stack Hub 中将 API 版本配置文件与 .NET 配合使用Use API version profiles with .NET in Azure Stack Hub

用于 Azure Stack Hub 资源管理器的 .NET SDK 提供了相关工具来帮助构建和管理基础结构。The .NET SDK for the Azure Stack Hub Resource Manager provides tools to help you build and manage your infrastructure. 该 SDK 中的资源提供程序包括了计算、网络、存储、应用服务和 Key VaultResource providers in the SDK include Compute, Networking, Storage, App Services, and Key Vault. .NET SDK 包括 14 NuGet 包。The .NET SDK includes 14 NuGet packages. 每次编译项目时,都必须将这些包下载到解决方案中。You must download these packages to your solution every time you compile your project. 不过,可以专门下载用于 2019-03-01-hybrid2018-03-01-hybrid 版本的资源提供程序,以便优化应用的内存。However, you can specifically download which resource provider you'll use for the 2019-03-01-hybrid or 2018-03-01-hybrid versions in order to optimize the memory for your app. 每个包都包含资源提供程序、相应的 API 版本以及所属 API 配置文件。Each package consists of a resource provider, the respective API version, and the API profile to which it belongs. .NET SDK 中的 API 配置文件可以用来在 Azure 资源和 Azure Stack Hub 上的资源之间进行切换,从而实现混合云开发。API profiles in the .NET SDK enable hybrid cloud development by helping you switch between Azure resources and resources on Azure Stack Hub.

.NET 与 API 版本配置文件.NET and API version profiles

API 配置文件是资源提供程序和 API 版本的组合。An API profile is a combination of resource providers and API versions. 可以使用 API 配置文件获取资源提供程序包中每个资源类型的最新且最稳定的版本。Use an API profile to get the latest, most stable version of each resource type in a resource provider package.

  • 若要使用所有服务的最新版本,请使用包的 latest 配置文件。To make use of the latest versions of all the services, use the latest profile of the packages. 该配置文件是 Microsoft.Azure.Management NuGet 包的一部分。This profile is part of the Microsoft.Azure.Management NuGet package.

  • 若要使用与 Azure Stack Hub 兼容的服务,请使用以下包之一:To use the services compatible with Azure Stack Hub, use one of the following packages:

    • Microsoft.Azure.Management.Profiles.hybrid_2019_03_01.<ResourceProvider>.0.9.0-preview.nupkgMicrosoft.Azure.Management.Profiles.hybrid_2019_03_01.<ResourceProvider>.0.9.0-preview.nupkg
    • Microsoft.Azure.Management.Profiles.hybrid_2018_03_01.<ResourceProvider>.0.9.0-preview.nupkgMicrosoft.Azure.Management.Profiles.hybrid_2018_03_01.<ResourceProvider>.0.9.0-preview.nupkg

    确保将上述 NuGet 包的 ResourceProvider 部分更改为正确的提供程序。Ensure that the ResourceProvider portion of the above NuGet package is changed to the correct provider.

  • 若要使用某个服务的最新 API 版本,请使用特定 NuGet 包的最新配置文件。To use the latest API version of a service, use the Latest profile of the specific NuGet package. 例如,若要单独使用计算服务的最新 API 版本,请使用 Compute 包的 最新配置文件。For example, if you want to use the latest-API version of the Compute service alone, use the latest profile of the Compute package. latest 配置文件是 Microsoft.Azure.Management NuGet 包的一部分。The latest profile is part of the Microsoft.Azure.Management NuGet package.

  • 若要使用特定资源提供程序中某个资源类型的特定 API 版本,请使用在包中定义的特定 API 版本。To use specific API versions for a resource type in a specific resource provider, use the specific API versions defined inside the package.

可以在同一应用程序中组合所有选项。You can combine all of the options in the same application.

安装 Azure .NET SDKInstall the Azure .NET SDK

  • 安装 Git。Install Git. 有关说明,请参阅入门 - 安装 GitFor instructions, see Getting Started - Installing Git.

  • 若要安装正确的 NuGet 包,请参阅查找和安装包To install the correct NuGet packages, see Finding and installing a package.

  • 需安装的包取决于要使用的配置文件版本。The packages that need to be installed depend on the profile version you want to use. 配置文件版本的包名如下:The package names for the profile versions are:

    • Microsoft.Azure.Management.Profiles.hybrid_2019_03_01.<ResourceProvider>.0.9.0-preview.nupkgMicrosoft.Azure.Management.Profiles.hybrid_2019_03_01.<ResourceProvider>.0.9.0-preview.nupkg

    • Microsoft.Azure.Management.Profiles.hybrid_2018_03_01.<ResourceProvider>.0.9.0-preview.nupkgMicrosoft.Azure.Management.Profiles.hybrid_2018_03_01.<ResourceProvider>.0.9.0-preview.nupkg

  • 若要安装 Visual Studio Code 的正确 NuGet 包,请查看此下载链接:NuGet 包管理器说明To install the correct NuGet packages for Visual Studio Code, see the following link to download the NuGet Package Manager instructions.

  • 如果不可用,请创建订阅,并保存订阅 ID 供稍后使用。If not available, create a subscription and save the subscription ID to be used later. 有关如何创建订阅的信息,请参阅在 Azure Stack Hub 中创建套餐的订阅For information about how to create a subscription, see Create subscriptions to offers in Azure Stack Hub.

  • 创建服务主体并保存客户端 ID 和客户端机密。Create a service principal and save the client ID and the client secret. 有关如何为 Azure Stack Hub 创建服务主体的信息,请参阅为应用程序提供对 Azure Stack Hub 的访问权限For information about how to create a service principal for Azure Stack Hub, see Provide applications access to Azure Stack Hub. 创建服务主体时的客户端 ID 也称为应用程序 ID。The client ID is also known as the application ID when creating a service principal.

  • 确保服务主体在订阅上具有“参与者/所有者”角色。Make sure your service principal has the contributor/owner role on your subscription. 有关如何将角色分配到服务主体的信息,请参阅为应用程序提供对 Azure Stack Hub 的访问权限For information about how to assign a role to service principal, see Provide applications access to Azure Stack Hub.

先决条件Prerequisites

若要将 .NET Azure SDK 与 Azure Stack Hub 配合使用,必须提供以下值,然后使用环境变量来设置值。To use the .NET Azure SDK with Azure Stack Hub, you must supply the following values, and then set the values with environment variables. 若要设置环境变量,请参阅表后针对特定操作系统的说明。To set the environmental variables, see the instructions following the table for your specific operating system.

ValueValue 环境变量Environment variables 说明Description
租户 IDTenant ID AZURE_TENANT_ID Azure Stack Hub [租户 ID][] 的值。The value of your Azure Stack Hub [tenant ID][].
客户端 IDClient ID AZURE_CLIENT_ID 在本文上一部分创建服务主体时保存的服务主体应用 ID。The service principal app ID saved when the service principal was created in the previous section of this article.
订阅 IDSubscription ID AZURE_SUBSCRIPTION_ID [订阅 ID][] 用于访问 Azure Stack Hub 中的套餐。The [subscription ID][] is how you access offers in Azure Stack Hub.
客户端机密Client Secret AZURE_CLIENT_SECRET 创建服务主体时保存的服务主体应用机密。The service principal app secret saved when the service principal was created.
资源管理器终结点Resource Manager Endpoint ARM_ENDPOINT 参阅 [Azure Stack Hub 资源管理器终结点][]。See [the Azure Stack Hub Resource Manager endpoint][].
位置Location RESOURCE_LOCATION Azure Stack Hub 的位置。Location of Azure Stack Hub.

若要查找 Azure Stack Hub 的租户 ID,请按照本文中的说明进行操作。To find the tenant ID for your Azure Stack Hub, follow the instructions in this article. 若要设置环境变量,请执行以下操作:To set your environment variables, do the following:

WindowsWindows

若要在 Windows 命令提示符中设置环境变量,请使用以下格式:To set the environment variables in a Windows command prompt, use the following format:

set Azure_Tenant_ID=Your_Tenant_ID

基于 MacOS、Linux 和 Unix 的系统MacOS, Linux, and Unix-based systems

在基于 Unix 的系统中,使用以下命令:In Unix-based systems, use the following command:

export Azure_Tenant_ID=Your_Tenant_ID

Azure Stack Hub 资源管理器终结点The Azure Stack Hub Resource Manager endpoint

Azure 资源管理器是一种管理框架,可供管理员用来部署、管理和监视 Azure 资源。Azure Resource Manager is a management framework that enables administrators to deploy, manage, and monitor Azure resources. Azure 资源管理器可以通过单个操作以组任务而不是单个任务的形式处理这些任务。Azure Resource Manager can handle these tasks as a group, rather than individually, in a single operation.

可以从资源管理器终结点获取元数据信息。You can get the metadata info from the Resource Manager endpoint. 该终结点返回 JSON 文件,其中包含运行代码所需的信息。The endpoint returns a JSON file with the info required to run your code.

请注意以下事项:Note the following considerations:

  • Azure Stack 开发工具包 (ASDK) 中的 ResourceManagerUrl 为: https://management.local.azurestack.external/The ResourceManagerUrl in the Azure Stack Development Kit (ASDK) is: https://management.local.azurestack.external/.

  • 集成系统中的 ResourceManagerUrlhttps://management.region.<fqdn>/,其中 <fqdn> 是完全限定的域名。The ResourceManagerUrl in integrated systems is: https://management.region.<fqdn>/, where <fqdn> is your fully qualified domain name. 检索所需的元数据:<ResourceManagerUrl>/metadata/endpoints?api-version=1.0To retrieve the metadata required: <ResourceManagerUrl>/metadata/endpoints?api-version=1.0.

示例 JSON 文件:Sample JSON file:

{
   "galleryEndpoint": "https://portal.local.azurestack.external:30015/",
   "graphEndpoint": "https://graph.chinacloudapi.cn/",
   "portal Endpoint": "https://portal.local.azurestack.external/",
   "authentication": 
      {
      "loginEndpoint": "https://login.chinacloudapi.cn/",
      "audiences": ["https://management.yourtenant.partner.onmschina.cn/3cc5febd-e4b7-4a85-a2ed-1d730e2f5928"]
      }
}

现有 API 配置文件Existing API profiles

  • Microsoft.Azure.Management.Profiles.hybrid_2019_03_01.<ResourceProvider>.0.9.0-preview.nupkg:为 Azure Stack Hub 生成的最新配置文件。Microsoft.Azure.Management.Profiles.hybrid_2019_03_01.<ResourceProvider>.0.9.0-preview.nupkg: Latest profile built for Azure Stack Hub. 使用此配置文件可以使服务与版本 1904 或更高版本的 Azure Stack Hub 最兼容。Use this profile for services to be most compatible with Azure Stack Hub, as long as you're on version 1904 or later.

  • Microsoft.Azure.Management.Profiles.hybrid_2018_03_01.<ResourceProvider>.0.9.0-preview.nupkg:使用此配置文件可以使服务与版本 1808 或更高版本的 Azure Stack Hub 兼容。Microsoft.Azure.Management.Profiles.hybrid_2018_03_01.<ResourceProvider>.0.9.0-preview.nupkg: Use this profile for services to be compatible with Azure Stack Hub for versions 1808 or later.

  • 最新:包含所有服务的最新版本的配置文件。Latest: Profile consisting of the latest versions of all services. 使用所有服务的最新版本。Use the latest versions of all the services. 该配置文件是 Microsoft.Azure.Management NuGet 包的一部分。This profile is part of the Microsoft.Azure.Management NuGet package.

有关 Azure Stack Hub 和 API 配置文件的详细信息,请参阅 [API 配置文件的摘要][]。For more information about Azure Stack Hub and API profiles, see the [Summary of API profiles][].

Azure .NET SDK API 配置文件的使用Azure .NET SDK API profile usage

使用以下代码来实例化资源管理客户端。Use the following code to instantiate a resource management client. 可以使用类似的代码来实例化其他资源提供程序客户端(例如计算、网络和存储)。Similar code can be used to instantiate other resource provider clients (such as Compute, Network, and Storage).

var client = new ResourceManagementClient(armEndpoint, credentials)
{
    SubscriptionId = subscriptionId;
};

此代码中的 credentials 参数是实例化客户端所需的。The credentials parameter in this code is required to instantiate a client. 以下代码根据租户 ID 和服务主体生成一个身份验证令牌:The following code generates an authentication token by the tenant ID and the service principal:

var azureStackSettings = getActiveDirectoryServiceSettings(armEndpoint);
var credentials = ApplicationTokenProvider.LoginSilentAsync(tenantId, servicePrincipalId, servicePrincipalSecret, azureStackSettings).GetAwaiter().GetResult();

代码中的 getActiveDirectoryServiceSettings 调用从元数据终结点检索 Azure Stack Hub 终结点。The getActiveDirectoryServiceSettings call in the code retrieves Azure Stack Hub endpoints from the metadata endpoint. 它从所做的调用声明环境变量:It states the environment variables from the call that's made:

public static ActiveDirectoryServiceSettings getActiveDirectoryServiceSettings(string armEndpoint)
{
    var settings = new ActiveDirectoryServiceSettings();
    try
    {
        var request = (HttpWebRequest)HttpWebRequest.Create(string.Format("{0}/metadata/endpoints?api-version=1.0", armEndpoint));
        request.Method = "GET";
        request.UserAgent = ComponentName;
        request.Accept = "application/xml";
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                var rawResponse = sr.ReadToEnd();
                var deserialized = JObject.Parse(rawResponse);
                var authenticationObj = deserialized.GetValue("authentication").Value<JObject>();
                var loginEndpoint = authenticationObj.GetValue("loginEndpoint").Value<string>();
                var audiencesObj = authenticationObj.GetValue("audiences").Value<JArray>();
                settings.AuthenticationEndpoint = new Uri(loginEndpoint);
                settings.TokenAudience = new Uri(audiencesObj[0].Value<string>());
                settings.ValidateAuthority = loginEndpoint.TrimEnd('/').EndsWith("/adfs", StringComparison.OrdinalIgnoreCase) ? false : true;
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(String.Format("Could not get AD service settings. Exception: {0}", ex.Message));
    }
    return settings;
}

按照这些步骤即可使用 API 配置文件 NuGet 包将应用程序成功部署到 Azure Stack Hub。These steps enable you to use the API profile NuGet packages to deploy your application successfully to Azure Stack Hub.

使用 API 配置文件的示例Samples using API Profiles

可以使用以下示例作为使用 .NET 和 Azure Stack Hub API 配置文件创建解决方案的参考:You can use the following samples as a reference for creating solutions with .NET and the Azure Stack Hub API profiles:

后续步骤Next steps

了解有关 API 配置文件的详细信息:Learn more about API profiles: