连接到媒体服务 v3 API - .NETConnect to Media Services v3 API - .NET

本文介绍如何使用服务主体登录方法连接到 Azure 媒体服务 v3 .NET SDK。This article shows you how to connect to the Azure Media Services v3 .NET SDK using the service principal login method.

先决条件Prerequisites

重要

查看命名约定Review naming conventions.

创建控制台应用程序Create a console application

  1. 启动 Visual Studio。Start Visual Studio.
  2. 在“文件”菜单中,单击“新建” > “项目”。 From the File menu, click New > Project.
  3. 创建 .NET Core 控制台应用程序。Create a .NET Core console application.

本主题中的示例应用面向 netcoreapp2.0The sample app in this topic, targets netcoreapp2.0. 代码使用从 C# 7.1 开始提供的“async main”。The code uses 'async main', which is available starting with C# 7.1. 有关更多详细信息,请参阅此博客See this blog for more details.

添加所需的 NuGet 包Add required NuGet packages

  1. 在 Visual Studio 中,选择“工具” > “NuGet 包管理器” > “NuGet 管理器控制台”。 In Visual Studio, select Tools > NuGet Package Manager > NuGet Manager Console.
  2. 在“包管理器控制台”窗口中,使用 Install-Package 命令添加以下 NuGet 包。In the Package Manager Console window, use Install-Package command to add the following NuGet packages. 例如,Install-Package Microsoft.Azure.Management.MediaFor example, Install-Package Microsoft.Azure.Management.Media.
程序包Package 说明Description
Microsoft.Azure.Management.Media Azure 媒体服务 SDK。Azure Media Services SDK.
为确保使用最新的 Azure 媒体服务包,请选中 Microsoft.Azure.Management.MediaTo make sure you are using the latest Azure Media Services package, check Microsoft.Azure.Management.Media.
Microsoft.Rest.ClientRuntime.Azure.Authentication 适用于 Azure SDK for NET 的 ADAL 身份验证库ADAL authentication library for Azure SDK for NET
Microsoft.Extensions.Configuration.EnvironmentVariables 读取环境变量和本地 JSON 文件中的配置值Read configuration values from environment variables and local JSON files
Microsoft.Extensions.Configuration.Json 读取环境变量和本地 JSON 文件中的配置值Read configuration values from environment variables and local JSON files
WindowsAzure.Storage 存储 SDKStorage SDK

创建并配置应用设置文件Create and configure the app settings file

创建 appsettings.jsonCreate appsettings.json

  1. 转到“常规” > “文本文件”。 Go go General > Text file.
  2. 将其命名为“appsettings.json”。Name it "appsettings.json".
  3. 将此 .json 文件的“复制到输出目录”属性设置为“如果较新则复制”(使应用程序能够在发布时访问此文件)。Set the "Copy to Output Directory" property of the .json file to "Copy if newer" (so that the application is able to access it when published).

设置 appsettings.json 中的值Set values in appsettings.json

根据访问 API 中所述运行 az ams account sp create 命令。Run the az ams account sp create command as described in access APIs. 该命令返回要复制到“appsettings.json”中的 JSON。The command returns json that you should copy into your "appsettings.json".

添加配置文件Add configuration file

为方便起见,请添加负责从“appsettings.json”读取值的配置文件。For convenience, add a configuration file that is responsible for reading values from "appsettings.json".

  1. 将新的 .cs 类添加到项目。Add a new .cs class to your project. 将它命名为 ConfigWrapperName it ConfigWrapper.
  2. 将以下代码粘贴到此文件中(本示例假设命名空间为 ConsoleApp1)。Paste the following code in this file (this example assumes you have the namespace is ConsoleApp1).
using System;

using Microsoft.Extensions.Configuration;

namespace ConsoleApp1
{
    public class ConfigWrapper
    {
        private readonly IConfiguration _config;

        public ConfigWrapper(IConfiguration config)
        {
            _config = config;
        }

        public string SubscriptionId
        {
            get { return _config["SubscriptionId"]; }
        }

        public string ResourceGroup
        {
            get { return _config["ResourceGroup"]; }
        }

        public string AccountName
        {
            get { return _config["AccountName"]; }
        }

        public string AadTenantId
        {
            get { return _config["AadTenantId"]; }
        }

        public string AadClientId
        {
            get { return _config["AadClientId"]; }
        }

        public string AadSecret
        {
            get { return _config["AadSecret"]; }
        }

        public Uri ArmAadAudience
        {
            get { return new Uri(_config["ArmAadAudience"]); }
        }

        public Uri AadEndpoint
        {
            get { return new Uri(_config["AadEndpoint"]); }
        }

        public Uri ArmEndpoint
        {
            get { return new Uri(_config["ArmEndpoint"]); }
        }

        public string Region
        {
            get { return _config["Region"]; }
        }
    }
}

连接到 .NET 客户端Connect to the .NET client

若要开始将媒体服务 API 与 .NET 结合使用,需要创建 AzureMediaServicesClient 对象。To start using Media Services APIs with .NET, you need to create an AzureMediaServicesClient object. 若要创建对象,需要提供客户端所需凭据以使用 Azure AD 连接到 Azure。To create the object, you need to supply credentials needed for the client to connect to Azure using Azure AD. 在以下代码中,GetCredentialsAsync 函数根据本地配置文件中提供的凭据创建 ServiceClientCredentials 对象。In the code below, the GetCredentialsAsync function creates the ServiceClientCredentials object based on the credentials supplied in local configuration file.

  1. 打开 Program.csOpen Program.cs.
  2. 粘贴以下代码:Paste the following code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.Azure.Management.Media;
using Microsoft.Azure.Management.Media.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
using Microsoft.Rest.Azure.Authentication;

namespace ConsoleApp1
{
    class Program
    {
        public static async Task Main(string[] args)
        {
            
            ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build());

            try
            {
                IAzureMediaServicesClient client = await CreateMediaServicesClientAsync(config);
                Console.WriteLine("connected");
            }
            catch (Exception exception)
            {
                if (exception.Source.Contains("ActiveDirectory"))
                {
                    Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample.");
                }

                Console.Error.WriteLine($"{exception.Message}");

                ApiErrorException apiException = exception.GetBaseException() as ApiErrorException;
                if (apiException != null)
                {
                    Console.Error.WriteLine(
                        $"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'.");
                }
            }

            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
        }
 
        private static async Task<ServiceClientCredentials> GetCredentialsAsync(ConfigWrapper config)
        {
            // Use ApplicationTokenProvider.LoginSilentWithCertificateAsync or UserTokenProvider.LoginSilentAsync to get a token using service principal with certificate
            //// ClientAssertionCertificate
            //// ApplicationTokenProvider.LoginSilentWithCertificateAsync

            // Use ApplicationTokenProvider.LoginSilentAsync to get a token using a service principal with symmetric key
            ClientCredential clientCredential = new ClientCredential(config.AadClientId, config.AadSecret);
            return await ApplicationTokenProvider.LoginSilentAsync(config.AadTenantId, clientCredential, ActiveDirectoryServiceSettings.AzureChina);
        }

        private static async Task<IAzureMediaServicesClient> CreateMediaServicesClientAsync(ConfigWrapper config)
        {
            var credentials = await GetCredentialsAsync(config);

            return new AzureMediaServicesClient(config.ArmEndpoint, credentials)
            {
                SubscriptionId = config.SubscriptionId,
            };
        }

    }
}

后续步骤Next steps

另请参阅See also