如何在Blazor .NET 8 Web应用中使用Microsoft Graph SDK?求可用示例
.NET 8 Blazor Web应用中使用Microsoft Graph SDK的可运行示例
1. 配置身份验证(以Azure AD为例)
在appsettings.json中添加Azure AD与Graph相关配置:
{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "你的租户域名.onmicrosoft.com", "TenantId": "你的租户ID", "ClientId": "你的应用客户端ID", "CallbackPath": "/signin-oidc" }, "Graph": { "Scopes": "User.Read Mail.Read" } }
2. 在Program.cs中注册身份验证与Graph服务
using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Identity.Web; using Microsoft.Identity.Web.UI; var builder = WebApplication.CreateBuilder(args); // 添加Azure AD身份验证服务 builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi(builder.Configuration.GetSection("Graph")["Scopes"]?.Split(' ')) .AddMicrosoftGraph(builder.Configuration.GetSection("Graph")) .AddInMemoryTokenCaches(); // 添加Blazor核心服务 builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddMicrosoftIdentityConsentHandler(); var app = builder.Build(); // 中间件配置 if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorComponents<App>() .AddInteractiveServerRenderMode(); app.Run();
3. 创建调用Graph API的Blazor组件
新建GraphUserInfo.razor组件,注入GraphServiceClient并调用API:
@page "/graph-user-info" @inject GraphServiceClient GraphClient @attribute [Authorize] <h3>当前用户信息(来自Microsoft Graph)</h3> @if (user != null) { <div> <p>姓名: @user.DisplayName</p> <p>邮箱: @user.Mail</p> <p>用户ID: @user.Id</p> @if (!string.IsNullOrEmpty(user.Photo?.ContentUrl)) { <img src="@user.Photo.ContentUrl" alt="用户头像" width="100" /> } </div> } else { <p>加载中...</p> } @code { private Microsoft.Graph.Models.User? user; protected override async Task OnInitializedAsync() { try { // 调用Graph API获取当前用户核心信息 user = await GraphClient.Me.GetAsync(requestConfiguration => { requestConfiguration.QueryParameters.Select = new[] { "displayName", "mail", "id", "photo" }; }); } catch (Exception ex) { Console.WriteLine($"调用Graph API出错: {ex.Message}"); } } }
关键注意事项
- 确保Azure AD应用已配置对应API权限(如
User.Read、Mail.Read),并完成管理员同意授权。 - 需额外安装
Microsoft.Identity.Web和Microsoft.Identity.Web.MicrosoftGraphNuGet包(它们会自动关联你已安装的Microsoft.Graph及Microsoft.Graph.Core依赖)。 - 上述示例适配.NET 8 Blazor Web App的Interactive Server模式,若使用Wasm模式,需调整客户端token获取逻辑。
内容的提问来源于stack exchange,提问作者MC94
相关产品推荐
相关产品推荐

