c# - 在 Azure Cosmos DB 中使用 REST 进行 CRUD 操作

标签 c# rest azure azure-cosmosdb

我正在尝试使用 REST 在 Azure Cosmos DB 上执行 CRUD 操作。根据链接 - https://learn.microsoft.com/en-us/rest/api/documentdb/create-a-document 我已经创建了我的有效负载并尝试在 Opera 浏览器中使用 Restman 来测试它。以下是我的有效负载详细信息-

标题

Authorization       ***************************

Content-Type        application/query+json

x-ms-date           Tue, 05 Dec 2017 16:49:31 GMT

x-ms-session-token  Session

x-ms-version        2017-02-22

正文

id        sg4c828f-31f8-4db4-8e7c-e8bdff222dsg

value     {     "id": "AndersenFamily",     "LastName": "Andersen",     "Parents": [       {         "FamilyName": null,         "FirstName": "Thomas"       },       {         "FamilyName": null,         "FirstName": "Mary Kay"       }     ],     "Children": [       {         "FamilyName": null,         "FirstName": "Henriette Thaulow",         "Gender": "female",         "Grade": 5,         "Pets": [           {             "GivenName": "Fluffy"           }         ]       }     ],     "Address": {       "State": "WA",       "County": "King",       "City": "Seattle"     },     "IsRegistered": true   }

放入请求 header 中的身份验证 token 已使用以下代码在 C# 中生成(根据上述链接中的示例)-

string GenerateAuthToken(string verb, string resourceType, string resourceId, string date, string key, string keyType, string tokenVersion)
{
    var hmacSha256 = new System.Security.Cryptography.HMACSHA256 { Key = Convert.FromBase64String(key) };

    verb = verb ?? "";
    resourceType = resourceType ?? "";
    resourceId = resourceId ?? "";

    string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
            verb.ToLowerInvariant(),
            resourceType.ToLowerInvariant(),
            resourceId,
            date.ToLowerInvariant(),
            ""
    );

    byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
    string signature = Convert.ToBase64String(hashPayLoad);

    return System.Web.HttpUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
        keyType,
        tokenVersion,
        signature));
}

这就是传递参数的方式-

GenerateAuthToken("GET", "dbs", "dbs/ToDoList", "Tue, 05 Dec 2017 16:49:31 GMT", PARENT_KEY, "master", "1.0");

所以当我向 URL 发出 POST 请求时 -

https://<account_name>.documents.azure.com:<port>/dbs/DCEAAA==/colls/DCEAAIcEVAA=/docs

我得到以下回复-

{ "code": "Unauthorized", "message": "The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'post\ndocs\ndceaaicevaa=\ntue, 05 dec 2017 16:49:31 gmt\n\n'\r\nActivityId: 7565996c-d008-438d-a1e9-744d4871948a, Microsoft.Azure.Documents.Common/1.19.121.4" }

我不知道这里到底出了什么问题。如果有人有任何想法,请告诉我。如需任何说明,请告诉我。

编辑:添加下面的 Restman 屏幕截图 - enter image description here

最佳答案

我跟进你提到的Document Create Document API,并做了一个演示,使用rest API创建documentdb文档。你可以引用一下。对于其他操作,您可以按照以下代码并构造哈希 token 。

根据Common Azure Cosmos DB REST request headers ,如果我们想创建一个文档,我们需要准备如下的标题

Authorization,x-ms-date,Content-Type,x-ms-version

我们可以从此 document 获取 x-m-version 。最新版本为2017-02-22

我们可以从这个document获取您提到的演示代码,关于如何构建主 token 的哈希 token 签名请引用此document 。从文档中我们可以知道resourceType可以是"dbs", "colls", "docs"。我们需要创建一个文档,所以resourceType = docs

var databaseId = "databaseName";
var collectionId = "collectionName";
var datetime = DateTime.UtcNow.ToString("R");
var verb = "post";
var resourceType = "docs"; //
var resourceId = $"dbs/{databaseId}/colls/{collectionId}";
var mastKey = "mastkey value";
var keyType = "master";
var tokenVersion = "1.0";
var authToken = GenerateAuthToken(verb, resourceType, resourceId, datetime, mastKey, keyType, tokenVersion);

我们还需要从上述代码变量datetime中获取x-ms-date

enter image description here

Post https://{documentDBAccount}.documents.azure.com:443/dbs/{databaseName}/colls/{collectionId}/docs 

enter image description here

更新:

请使用以下数据作为json正文

{
    "id": "sg4c828f-31f8-4db4-8e7c-e8bdff222dsg",
    "value": {
        "id": "AndersenFamily",
        "LastName": "Andersen",
        "Parents": [
            {
                "FamilyName": null,
                "FirstName": "Thomas"
            },
            {
                "FamilyName": null,
                "FirstName": "Mary Kay"
            }
        ],
        "Children": [
            {
                "FamilyName": null,
                "FirstName": "Henriette Thaulow",
                "Gender": "female",
                "Grade": 5,
                "Pets": [
                    {
                        "GivenName": "Fluffy"
                    }
                ]
            }
        ],
        "Address": {
            "State": "WA",
            "County": "King",
            "City": "Seattle"
        },
        "IsRegistered": true
    }
}

enter image description here

关于c# - 在 Azure Cosmos DB 中使用 REST 进行 CRUD 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47659609/

相关文章:

wcf - 在 IIS 6 上启用 WCF REST Api 上的 PUT(没有 .svc 文件)

ios - 从我的 iPhone 或 Blackberry 访问本地托管的 Web 服务

java - 通过客户端触发 Restful 服务器响应

c# - 以编程方式登录到 Azure Active Directory

rest - Azure 函数 REST API 处理 GET POST

c# - 反射和继承问题c#

c# - 如何进行回调以删除另一个类中存在的类的实例?

c# - 在根中插入证书(带有私钥),.NET 4 中的本地计算机证书存储失败

c# - 将 List<XElement> 转换为 DataTable

python - 使用 %sql 语句设置 databricks python 变量