You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Azure Media Service获取Locator流URL至C#控制器?

嘿,我来帮你搞定在C#控制器里获取Azure Media Services(AMS)Locator流URL的需求!这里有两种常用方案,推荐用官方SDK更省心,当然也可以直接调用REST API,我都给你列出来:

获取AMS Locator流URL的C#实现

方案一:使用Azure Media Services .NET SDK(推荐)

官方SDK封装了认证、资源调用等细节,比直接写REST请求更简洁易维护。

第一步:安装NuGet包

先把最新的AMS管理SDK安装到项目里:

Install-Package Azure.ResourceManager.Media

第二步:控制器代码示例

在你的API控制器里,可以这样实现获取Locator流URL的接口:

using Azure.Identity;
using Azure.ResourceManager.Media;
using Azure.ResourceManager.Media.Models;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/media")]
public class MediaController : ControllerBase
{
    private readonly MediaServicesAccountResource _mediaAccount;

    // 从配置读取Azure信息,初始化AMS客户端
    public MediaController(IConfiguration configuration)
    {
        var subscriptionId = configuration["Azure:SubscriptionId"];
        var resourceGroupName = configuration["Azure:ResourceGroupName"];
        var accountName = configuration["Azure:MediaAccountName"];

        var armClient = new ArmClient(new DefaultAzureCredential());
        var subscription = armClient.GetSubscriptionResource(new ResourceIdentifier($"/subscriptions/{subscriptionId}"));
        var resourceGroup = subscription.GetResourceGroup(resourceGroupName);
        _mediaAccount = resourceGroup.GetMediaServicesAccount(accountName);
    }

    [HttpGet("locator-url/{locatorId}")]
    public async Task<IActionResult> GetStreamingLocatorUrl(string locatorId)
    {
        try
        {
            // 根据ID获取指定的Streaming Locator
            var locator = await _mediaAccount.GetStreamingLocatorAsync(locatorId);
            
            // 获取默认的Streaming Endpoint(如果用了自定义Endpoint,替换成你的名称)
            var streamingEndpoint = await _mediaAccount.GetStreamingEndpointAsync("default");
            
            // 拼接完整的流URL:Endpoint主机名 + Locator路径
            var streamUrl = $"https://{streamingEndpoint.Value.HostName}{locator.Value.Path}";

            return Ok(new { StreamingUrl = streamUrl });
        }
        catch (Exception ex)
        {
            return BadRequest($"获取Locator URL失败:{ex.Message}");
        }
    }
}

提示:DefaultAzureCredential会自动适配Azure环境(比如App Service、VM)的认证,本地开发时会用你登录Azure CLI的账号,确保账号有Media Services Contributor权限。

方案二:直接调用REST API(对应你参考的官方文档)

如果一定要手动调用REST接口,需要先处理Azure AD认证,再发送请求解析响应:

控制器代码示例

using System.Net.Http.Headers;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/media")]
public class MediaRestController : ControllerBase
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;

    public MediaRestController(HttpClient httpClient, IConfiguration configuration)
    {
        _httpClient = httpClient;
        _configuration = configuration;
    }

    [HttpGet("rest-locator-url/{locatorId}")]
    public async Task<IActionResult> GetLocatorUrlViaRest(string locatorId)
    {
        try
        {
            // 1. 获取Azure AD访问令牌
            var accessToken = await GetAadAccessToken();
            if (string.IsNullOrEmpty(accessToken))
            {
                return Unauthorized("无法获取Azure AD认证令牌");
            }

            // 2. 构造REST请求URL
            var accountName = _configuration["Azure:MediaAccountName"];
            var location = _configuration["Azure:MediaAccountLocation"]; // 比如"eastus"
            var requestUrl = $"https://{accountName}.restv2.{location}.media.azure.net/api/Locators('nb:lid:UUID:{locatorId}')";

            // 3. 设置请求头并发送GET请求
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _httpClient.DefaultRequestHeaders.Add("DataServiceVersion", "3.0");
            _httpClient.DefaultRequestHeaders.Add("MaxDataServiceVersion", "3.0");

            var response = await _httpClient.GetAsync(requestUrl);
            response.EnsureSuccessStatusCode();

            // 4. 解析响应,提取Locator路径并拼接流URL
            var responseContent = await response.Content.ReadAsStringAsync();
            var locatorJson = JsonDocument.Parse(responseContent).RootElement.GetProperty("d");
            var locatorPath = locatorJson.GetProperty("Path").GetString();
            
            // 这里的Streaming Endpoint主机名可以提前配置,或者调用另一个REST接口获取
            var streamingHost = _configuration["Azure:StreamingEndpointHost"]; // 比如"youraccount.streaming.media.azure.net"
            var streamUrl = $"https://{streamingHost}{locatorPath}";

            return Ok(new { StreamingUrl = streamUrl });
        }
        catch (Exception ex)
        {
            return BadRequest($"调用REST API失败:{ex.Message}");
        }
    }

    // 获取Azure AD服务主体令牌
    private async Task<string> GetAadAccessToken()
    {
        var tenantId = _configuration["Azure:TenantId"];
        var clientId = _configuration["Azure:ClientId"];
        var clientSecret = _configuration["Azure:ClientSecret"];
        var resource = "https://rest.media.azure.net";

        var tokenRequest = new Dictionary<string, string>
        {
            ["grant_type"] = "client_credentials",
            ["client_id"] = clientId,
            ["client_secret"] = clientSecret,
            ["resource"] = resource
        };

        var tokenResponse = await _httpClient.PostAsync(
            $"https://login.microsoftonline.com/{tenantId}/oauth2/token",
            new FormUrlEncodedContent(tokenRequest));
        tokenResponse.EnsureSuccessStatusCode();

        var tokenContent = await tokenResponse.Content.ReadAsStringAsync();
        var tokenJson = JsonDocument.Parse(tokenContent).RootElement;
        return tokenJson.GetProperty("access_token").GetString();
    }
}

提示:这种方式需要在Azure AD注册服务主体,并给它分配AMS的访问权限,配置里要填好TenantId、ClientId、ClientSecret这些信息。

内容的提问来源于stack exchange,提问作者raspi surya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:06:26