你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
本指南演示如何生成 .NET 控制台应用程序以连接到 Azure Cosmos DB for MongoDB vCore 群集。 设置开发环境,使用 Azure.Identity
用于 .NET 的 Azure SDK 中的库进行身份验证,并与数据库交互以创建、查询和更新文档。
先决条件
- 现有的 Azure Cosmos DB for MongoDB (vCore) 群集。
Azure Cloud Shell 中最新版本的 Azure CLI。
- 如果想要在本地运行 CLI 引用命令,请使用
az login
该命令登录到 Azure CLI。
- 如果想要在本地运行 CLI 引用命令,请使用
检索 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-cosmos-db-mongodb-vcore-cluster-name>"; MongoUrl url = MongoUrl.Create($"mongodb+srv://{clusterName}.global.mongocluster.cosmos.azure.com/");
使用在前面步骤中创建的
MongoSettings
以及 Azure Cosmos DB for MongoDB vCore 的标准最佳做法配置,来配置新的MongoUrl
实例。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<>.ReplaceOneAsync
Product 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