为 Azure 媒体服务资产创建按需定位器时出现异常

Exception when creating on demand loactor for Azure Media Services asset

我正在使用 Azure Functions 访问 Azure 媒体服务。我有一个 HTTP 触发器,可以让我获得视频文件的流式传输 link。 当我尝试创建点播流定位器时,服务器有时 return 出现以下错误:

One or more errors occurred. Microsoft.WindowsAzure.MediaServices.Client: An error occurred while processing this request. Locator's ExpirationDateTime cannot be in the past.

部分代码如下:

using System.Net;
using Microsoft.WindowsAzure.MediaServices.Client;
...
public static readonly TimeSpan ExpirationTimeThreshold = TimeSpan.FromHours(5);
public static readonly DateTime TimeSkew = DateTime.UtcNow.AddMinutes(-5);
...

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    string assetId = req.GetQueryNameValuePairs().FirstOrDefault(q => string.Compare(q.Key, "assetId", true) == 0).Value;

    IAsset wantedAsset = _context.Assets.Where(a => a.Id.Equals(assetId)).FirstOrDefault();

    if (wantedAsset == null)
    {
        return req.CreateResponse(HttpStatusCode.BadRequest,
        "No asset matches the Id");

    }

    originLocator = wantedAsset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin).FirstOrDefault();

    if (originLocator == null)
    {
        IAccessPolicy policy = _context.AccessPolicies.Create("Streaming policy",
        ExpirationTimeThreshold,
        AccessPermissions.Read);

        originLocator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, wantedAsset,
        policy, 
        TimeSkew); //This is where the exception is returned
    }
    ...
}

这似乎是一种非常不一致的行为,因为它在大多数情况下都会按预期工作。 有一次发生这种情况时,我尝试在 Azure 函数中输入日志语句,当我保存更改时,该函数按预期工作。

我在写这篇文章时意识到的一件事是,在我将更改保存到 Azure Functions 之前,TimeSkew 变量不会更新。 这意味着这是第一次 运行,例如 TimeSkew 将是 5:00PM,5 小时后 TimeSkew 仍将是 5:00PM,这意味着 ExpirationTimeThresholdTimeSkew会互相取反吗?

TimeSkew 设置为局部变量应该可以解决我的问题?

我想你已经回答了你自己的问题。每次重新编译时(或更具体地说,每次新实例启动 运行ning 您的函数时),都会初始化 TimeSkew 静态变量。对于同一实例的所有后续请求,TimeSkew 值保持不变,这可能会导致上述错误。

解决方案:不要将任何静态变量初始化为 DateTime.Now 相关的东西,除非你真的想在每个实例上跟踪第一个 运行 的开始时间(你不需要) .