你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
本指南演示如何生成 .NET 控制台应用程序以连接到 Azure DocumentDB 群集。 设置开发环境,使用 Azure.Identity 用于 .NET 的 Azure SDK 中的库进行身份验证,并与数据库交互以创建、查询和更新文档。
先决条件
Azure 订阅服务
- 如果没有 Azure 订阅,请创建 一个免费帐户
现有的 Azure DocumentDB 群集
- 如果没有群集,请 创建新群集
在 Azure Cloud Shell 中使用 Bash 环境。 有关详细信息,请参阅 Azure Cloud Shell 入门。
如需在本地运行 CLI 参考命令,请安装 Azure CLI。 如果在 Windows 或 macOS 上运行,请考虑在 Docker 容器中运行 Azure CLI。 有关详细信息,请参阅如何在 Docker 容器中运行 Azure CLI。
如果使用的是本地安装,请使用 az login 命令登录到 Azure CLI。 若要完成身份验证过程,请遵循终端中显示的步骤。 有关其他登录选项,请参阅 使用 Azure CLI 向 Azure 进行身份验证。
出现提示时,请在首次使用时安装 Azure CLI 扩展。 有关扩展的详细信息,请参阅 使用和管理 Azure CLI 中的扩展。
运行az version命令,以查看已安装的版本和依赖库。 若要升级到最新版本,请运行az upgrade。
检索 Microsoft Entra 租户元数据
若要使用 TokenCredential 类在 Azure.Identity 中检索访问令牌,您需要 Microsoft Entra 租户的唯一标识符。 在此先决条件步骤中,使用 Azure CLI 检索和记录 tenantId 值。
使用
az account show获取当前登录的 Azure 订阅的详细信息。az account show该命令将输出包含各种字段的 JSON 响应。
{ "environmentName": "AzureCloud", "homeTenantId": "eeeeffff-4444-aaaa-5555-bbbb6666cccc", "id": "dddd3d3d-ee4e-ff5f-aa6a-bbbbbb7b7b7b", "isDefault": true, "managedByTenants": [], "name": "example-azure-subscription", "state": "Enabled", "tenantId": "eeeeffff-4444-aaaa-5555-bbbb6666cccc", "user": { "cloudShellID": true, "name": "kai@adventure-works.com", "type": "user" } }记录
tenantId属性的值。 此属性是Microsoft Entra 租户的唯一标识符,有时称为 租户 ID。 您可以在后续章节的步骤中使用该值。
配置控制台应用程序
接下来,创建新的控制台应用程序项目,并导入必要的库以向群集进行身份验证。
在空目录中,创建新的 .NET 控制台应用程序。
dotnet new console从 NuGet 导入
Azure.Identity包。dotnet add package Azure.Identity接下来,导入
MongoDB.Driver包。dotnet add package MongoDB.Driver生成 .NET 项目
dotnet build
连接至群集
现在,使用 Azure.Identity 库获取一个 TokenCredential,以用于连接到您的群集。 官方 MongoDB 驱动程序具有一个特殊接口,必须实现该接口,以便从 Microsoft Entra 获取令牌,以便在连接到群集时使用。
在 Program.cs 文件中,为这些
Azure.Identity和MongoDB.Driver命名空间添加使用块。using Azure.Identity; using MongoDB.Driver;在一个单独的文件中,创建一个实现
MongoDB.Driver.Authentication.Oidc.IOidcCallback接口所有必需成员的新类。using Azure.Core; using MongoDB.Driver.Authentication.Oidc; internal sealed class AzureIdentityTokenHandler( TokenCredential credential, string tenantId ) : IOidcCallback { private readonly string[] scopes = ["https://ossrdbms-aad.database.windows.net/.default"]; public OidcAccessToken GetOidcAccessToken(OidcCallbackParameters parameters, CancellationToken cancellationToken) { AccessToken token = credential.GetToken( new TokenRequestContext(scopes, tenantId: tenantId), cancellationToken ); return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow); } public async Task<OidcAccessToken> GetOidcAccessTokenAsync(OidcCallbackParameters parameters, CancellationToken cancellationToken) { AccessToken token = await credential.GetTokenAsync( new TokenRequestContext(scopes, parentRequestId: null, tenantId: tenantId), cancellationToken ); return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow); } }小窍门
为了说明目的,该类被命名为
AzureIdentityTokenHandler。 可以将此类命名为所需的任何内容。 本指南的其余部分假定类已命名AzureIdentityTokenHandler。返回到 Program.cs 文件的编辑器。
使用现有群集的名称创建字符串变量。 然后,使用
MongoUrl将该变量创建为类型为MongoUrl.Create的新实例。string clusterName = "<azure-documentdb-cluster-name>"; MongoUrl url = MongoUrl.Create($"mongodb+srv://{clusterName}.global.mongocluster.cosmos.azure.com/");使用在前面步骤中创建的
MongoUrl和 Azure DocumentDB 的标准最佳实践来配置一个新的MongoSettings实例。MongoClientSettings settings = MongoClientSettings.FromUrl(url); settings.UseTls = true; settings.RetryWrites = false; settings.MaxConnectionIdleTime = TimeSpan.FromMinutes(2);创建新凭据,其类型为
DefaultAzureCredential。DefaultAzureCredential credential = new();小窍门
在此处可以使用任何类型为
TokenCredential的凭据。DefaultAzureCredential是早期开发方案最无摩擦的选项。创建一个实现
IOidcCallback的类的新实例,并使用本指南前面记录的租户 ID进行配置。string tenantId = "<microsoft-entra-tenant-id>"; AzureIdentityTokenHandler tokenHandler = new(credential, tenantId);使用
MongoCredential.CreateOidcCredential配置设置的凭据,并传入自定义处理程序回调实现。settings.Credential = MongoCredential.CreateOidcCredential(tokenHandler);冻结设置,然后创建一个
MongoClient新实例。settings.Freeze(); MongoClient client = new(settings); Console.WriteLine("Client created");
执行常见操作
最后,使用官方库对数据库、集合和文档执行常见任务。 在这里,你将使用相同的类和方法与 MongoDB 或 DocumentDB 进行交互来管理集合和项。
通过在自己的文件中创建自定义记录类型来表示文档。
public record Product( string id, string category, string name, int quantity, decimal price, bool clearance );小窍门
为了说明目的,此结构命名
Product。 本指南的其余部分假定已定义此结构。返回 Program.cs 文件。
使用
MongoClient.GetDatabase获取一个指向您的数据库的指针。string databaseName = "<database-name>"; IMongoDatabase database = client.GetDatabase(databaseName); Console.WriteLine("Database pointer created");然后,使用数据库指针通过
IMongoDatabase.GetCollection<>获取指向集合的指针。string collectionName = "<collection-name>"; IMongoCollection<Product> collection = database.GetCollection<Product>(collectionName); Console.WriteLine("Collection pointer created");使用 方法创建和更新插入两个文档。
IMongoCollection<>.ReplaceOneAsyncProduct classicSurfboard = new( id: "bbbbbbbb-1111-2222-3333-cccccccccccc", category: "gear-surf-surfboards", name: "Kiama Classic Surfboard", quantity: 25, price: 790.00m, clearance: false ); Product paddleKayak = new( id: "cccccccc-2222-3333-4444-dddddddddddd", category: "gear-paddle-kayaks", name: "Lastovichka Paddle Kayak", quantity: 10, price: 599.99m, clearance: true ); await collection.ReplaceOneAsync<Product>( doc => doc.id == classicSurfboard.id, classicSurfboard, new ReplaceOptions { IsUpsert = true } ); Console.WriteLine($"Upserted document:\t{classicSurfboard.id}"); await collection.ReplaceOneAsync<Product>( doc => doc.id == paddleKayak.id, paddleKayak, new ReplaceOptions { IsUpsert = true } ); Console.WriteLine($"Upserted document:\t{paddleKayak.id}");使用
IMongoCollection<>.Find和IFindFluent<,>.SingleAsync. 从集合中读取单个文档。 使用筛选器指定要查找的特定文档。Product document = await collection.Find( doc => doc.id == "cccccccc-2222-3333-4444-dddddddddddd" ).SingleAsync(); Console.WriteLine($"Found document:\t{document.name}");查询使用相同
Find方法匹配筛选器的所有文档。 使用筛选器定义特定属性(如category)和特定值(如gear-surf-surfboards)。 使用IFindFluent<,>.ToListAsync枚举结果。List<Product> documents = await collection.Find( doc => doc.category == "gear-surf-surfboards" ).ToListAsync(); foreach (Product doc in documents) { Console.WriteLine($"Queried document:\t{doc}"); }使用
IMongoCollection<>.DeleteOneAsync筛选器从集合中删除特定文档。await collection.DeleteOneAsync( doc => doc.id == "bbbbbbbb-1111-2222-3333-cccccccccccc" ); Console.WriteLine($"Deleted document");保存 项目中的所有代码文件。
使用
dotnet run运行项目dotnet run观察正在运行的应用程序的输出。
Client created Database pointer created Collection pointer created Upserted document: bbbbbbbb-1111-2222-3333-cccccccccccc Upserted document: cccccccc-2222-3333-4444-dddddddddddd Found document: Lastovichka Paddle Kayak Queried document: Product { id = bbbbbbbb-1111-2222-3333-cccccccccccc, category = gear-surf-surfboards, name = Kiama Classic Surfboard, quantity = 25, price = 790.00, clearance = False } Deleted document