DocumentDB - 連線賬戶



當您開始對 DocumentDB 進行程式設計時,第一步就是連線。因此,要連線到您的 DocumentDB 帳戶,您需要兩樣東西:

  • 端點
  • 授權金鑰

端點

端點是您 DocumentDB 帳戶的 URL,它是透過將您的 DocumentDB 帳戶名稱與 .documents.azure.com 組合來構建的。讓我們轉到儀表板。

Endpoint

現在,點選建立的 DocumentDB 帳戶。您將看到如下所示的詳細資訊。

click on created DocumentDB

當您選擇“金鑰”選項時,它將顯示如下所示的其他資訊。您還將看到 DocumentDB 帳戶的 URL,您可以將其用作端點。

select keys option

授權金鑰

授權金鑰包含您的憑據,並且有兩種型別的金鑰。主金鑰允許完全訪問帳戶中的所有資源,而資源令牌允許對特定資源進行受限訪問。

主金鑰

  • 使用主金鑰,您幾乎可以做任何事情。如果您願意,可以使用主金鑰刪除整個資料庫。

  • 因此,您絕對不想共享主金鑰或將其分發到客戶端環境。作為一項額外的安全措施,最好經常更改它。

  • 每個資料庫帳戶實際上有兩個主金鑰,即主金鑰和輔助金鑰,如上圖所示。

資源令牌

  • 您也可以使用資源令牌代替主金鑰。

  • 基於資源令牌的連線只能訪問令牌指定的資源,而不能訪問其他資源。

  • 資源令牌基於使用者許可權,因此首先您建立一個或多個使用者,這些使用者是在資料庫級別定義的。

  • 您可以為每個使用者建立一個或多個許可權,這些許可權基於您希望允許每個使用者訪問的資源。

  • 每個許可權都會生成一個資源令牌,該令牌允許對給定資源進行只讀或完全訪問,並且該資源可以是資料庫中的任何使用者資源。

讓我們轉到第 3 章中建立的控制檯應用程式。

步驟 1 - 在 Program.cs 檔案中新增以下引用。

using Microsoft.Azure.Documents; 
using Microsoft.Azure.Documents.Client; 
using Microsoft.Azure.Documents.Linq; 
using Newtonsoft.Json;

步驟 2 - 現在新增端點 URL 和授權金鑰。在本例中,我們將使用主金鑰作為授權金鑰。

請注意,在您的情況下,端點 URL 和授權金鑰都應該不同。

private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/"; 
private const string AuthorizationKey = 
   "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";

步驟 3 - 在名為 CreateDocumentClient 的非同步任務中建立一個 DocumentClient 的新例項,並例項化新的 DocumentClient。

步驟 4 - 從您的 Main 方法呼叫您的非同步任務。

以下是迄今為止完整的 Program.cs 檔案。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
using System.Threading.Tasks;

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Newtonsoft.Json;

namespace DocumentDBDemo { 

   class Program {
      private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/";
		
      private const string AuthorizationKey = "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/
         StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ==";
			
      static void Main(string[] args) {
         try {
            CreateDocumentClient().Wait();
         } catch (Exception e) {
            Exception baseException = e.GetBaseException();
            Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message);
         }
			
         Console.ReadKey();
      }
		
      private static async Task CreateDocumentClient() {
         // Create a new instance of the DocumentClient
         var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);
      }
		
   }
}

在本章中,我們學習瞭如何連線到 DocumentDB 帳戶並建立 DocumentClient 類的例項。

廣告

© . All rights reserved.