Share via


Verbinding maken met Media Services v3-API - .NET

Media Services-logo v3


Waarschuwing

Azure Media Services wordt op 30 juni 2024 buiten gebruik gesteld. Zie de Handleiding voor buitengebruikstelling van AMS voor meer informatie.

In dit artikel wordt beschreven hoe u verbinding maakt met de Azure Media Services v3 .NET SDK met behulp van de aanmeldingsmethode voor de service-principal.

Vereisten

Belangrijk

Bekijk naamconventies.

Een consoletoepassing maken

  1. Start Visual Studio.
  2. Klik in het menu Bestand op Nieuw>project.
  3. Maak een .NET Core-consoletoepassing .

De voorbeeld-app in dit onderwerp is gericht op netcoreapp2.0. De code maakt gebruik van 'asynchrone main', die beschikbaar is vanaf C# 7.1. Zie deze blog voor meer informatie.

Vereiste NuGet-pakketten/assembly's toevoegen

  1. Selecteer in Visual Studio Tools>NuGet Package Manager>NuGet Manager Console.
  2. Gebruik in het venster Install-PackagePackage Manager Console de opdracht om de volgende NuGet-pakketten toe te voegen. Bijvoorbeeld Install-Package Microsoft.Azure.Management.Media.
Pakket Beschrijving
Microsoft.Azure.Management.Media Azure Media Services SDK.
Als u zeker wilt weten dat u het meest recente Azure Media Services-pakket gebruikt, raadpleegt u Microsoft.Azure.Management.Media.

Andere vereiste assembly's

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

Het app-instellingenbestand maken en configureren

Appsettings.json maken

  1. Ga naar Algemeen>tekstbestand.
  2. Geef deze de naam 'appsettings.json'.
  3. Stel de eigenschap 'Kopiëren naar uitvoermap' van het .json-bestand in op 'Kopiëren indien nieuwer' (zodat de toepassing er toegang toe heeft wanneer het wordt gepubliceerd).

Waarden instellen in appsettings.json

Voer de az ams account sp create opdracht uit zoals beschreven in Access API's. De opdracht retourneert json die u moet kopiëren naar uw 'appsettings.json'.

Een configuratiebestand toevoegen

Voeg voor het gemak een configuratiebestand toe dat verantwoordelijk is voor het lezen van waarden uit 'appsettings.json'.

  1. Voeg een nieuwe .cs-klasse toe aan uw project. Noem deze ConfigWrapper.
  2. Plak de volgende code in dit bestand (in dit voorbeeld wordt ervan uitgegaan dat u de naamruimte hebt.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"]; }
        }
    }
}

Verbinding maken met de .NET-client

Als u wilt starten met Media Services API's met .NET, moet u een AzureMediaServicesClient-object maken. Als u het object wilt maken, moet u referenties opgeven die de client nodig heeft om verbinding te maken met Azure met behulp van Microsoft Azure Active Directory. In de onderstaande code maakt de functie GetCredentialsAsync het ServiceClientCredentials-object op basis van de referenties die zijn opgegeven in het lokale configuratiebestand.

  1. Open Program.cs.
  2. Plak de volgende 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}");


                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,
            };
        }

    }
}

Help en ondersteuning

U kunt contact opnemen met Media Services met vragen of onze updates op een van de volgende manieren volgen: