如何从 C# 查询 Cosmos DB 集合



从 C# 连接到 Cosmosdb 时出现以下错误。

输入授权令牌无法为请求提供服务。请检查预期的有效负载是否按照协议构建,并检查正在使用的密钥。服务器使用以下有效负载进行签名:

'get
wed, 07 aug 2019 13:20:12 gmt
ActivityId: 01489e82-0586-44d0-878d-0cc8cee22852, Microsoft.Azure.Documents.Common/2.5.1, Windows/10.0.15063 documentdb-netcore-sdk/2.4.0

using Microsoft.Azure.Documents.Client;
using System;
using System.Linq;
namespace DeviceCount
{
class Program
{
private static readonly string EndpointUri = "aaaa";
private static readonly string PrimaryKey = "bbb";
private static readonly string DBName = "ccc";
static void Main(string[] args)
{
DateTime currentTime = DateTime.Now;
var currentEpochTime = (int)currentTime.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
var currentTimeMinusOneH = DateTime.Now.AddHours(-1);
var currentEpochTimeMinusOneH = (int)currentTimeMinusOneH.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
ConnectionPolicy connectionPolicy = new ConnectionPolicy();
connectionPolicy.ConnectionMode = ConnectionMode.Gateway;
using (var client = new DocumentClient(new Uri(EndpointUri), PrimaryKey, connectionPolicy))
{
client.OpenAsync().Wait();

var response = client.CreateDocumentQuery
(UriFactory.CreateDocumentCollectionUri(DBName, "ddddd"),
"SELECT value count(c.id) FROM ddddd c where c._ts between " + currentEpochTime + " and " + currentEpochTimeMinusOneH).ToList();
var document = response.First();
Console.WriteLine($"Id:{document.id}");
Console.ReadLine();
}
}
}
}

似乎问题出在令牌中,因为根据错误,您需要授权标头中主令牌的有效签名哈希才能对 Cosmosdb 执行 REST 调用。

签名哈希由操作的 REST 谓词、资源类型、资源 ID 和 UTC 日期时间组成。 您需要为每个operation构造一个新的签名哈希。

最新更新