Share via


Media Services v3 API に接続する - .NET

Media Services ロゴ v3


警告

Azure Media Services は、2024 年 6 月 30 日に廃止されます。 詳細については、「 AMS 廃止ガイド」を参照してください。

この記事では、サービス プリンシパルによるログイン方式を使用して Azure Media Services v3 .NET SDK に接続する方法を説明します。

前提条件

重要

命名規則を確認してください。

コンソール アプリケーションの作成

  1. Visual Studio を起動します。
  2. [ファイル] メニューから [新規作成]>[プロジェクト] をクリックします。
  3. .NET Core コンソール アプリケーションを作成します。

このトピックのサンプル アプリの対象は netcoreapp2.0 です。 コードでは "async main" が使用されています。これは、C# 7.1 以降で利用できます。 詳しくは、こちらのブログをご覧ください。

必要な NuGet パッケージおよびアセンブリを追加する

  1. Visual Studio で、 [ツール]>[NuGet パッケージ マネージャー]>[NuGet Manager Console](NuGet マネージャー コンソール) の順に選択します。
  2. [パッケージ マネージャー コンソール] ウィンドウで、Install-Package コマンドを使用して次の NuGet パッケージを追加します。 たとえば、「 Install-Package Microsoft.Azure.Management.Media 」のように入力します。
Package 説明
Microsoft.Azure.Management.Media Azure Media Services SDK。
最新の Azure Media Services パッケージを使用していることを確認するには、Microsoft.Azure.Management.Media をチェックします。

その他の必要なアセンブリ

  • Azure.Storage.Blobs
  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Configuration.Json
  • Microsoft.Rest.ClientRuntime.Azure.Authentication

アプリ設定ファイルを作成して構成する

appsettings.json を作成する

  1. [全般]>[テキスト ファイル] に移動します。
  2. "appsettings.json" という名前に設定します。
  3. .json ファイルの [出力ディレクトリにコピー] プロパティを [新しい場合はコピーする] に設定します (発行されたときにアプリケーションがアクセスできるように)。

appsettings.json の値を設定する

API へのアクセスに関する記事の説明に従って、az ams account sp create コマンドを実行します。 コマンドで返される json を、"appsettings.json" にコピーする必要があります。

Add configuration file

便利なように、"appsettings.json" から値を読み取る構成ファイルを追加します。

  1. 新しい .cs クラスをプロジェクトに追加します。 これに ConfigWrapper という名前を付けます。
  2. 次のコードをこのファイルに貼り付けます (この例では、名前空間が 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 Location
        {
            get { return _config["Location"]; }
        }
    }
}

.NET クライアントに接続する

.NET で Media Services API の使用を始めるには、AzureMediaServicesClient オブジェクトを作成する必要があります。 オブジェクトを作成するには、クライアントが Azure AD を使用して Azure に接続するために必要な資格情報を指定する必要があります。 次のコードでは、ローカル構成ファイルで指定された資格情報に基づいて、GetCredentialsAsync 関数により ServiceClientCredentials オブジェクトが作成されます。

  1. Program.csを開きます。
  2. 次のコードを貼り付けます。
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}");


                if (exception.GetBaseException() is ErrorResponseException apiException)
                {
                    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.Azure);
        }

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

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

    }
}

ヘルプとサポート

Media Services に質問がある場合は、次のいずれかの方法で更新プログラムに従ってください。

  • Q & A
  • Stack Overflow。 質問に タグを付け、 を使用します azure-media-services
  • @MSFTAzureMedia するか 、@AzureSupport を使用してサポートを要求します。
  • Azure portalからサポート チケットを開きます。