教程:使用 Microsoft Graph SDK 创建 .NET MAUI 应用
通过在 Windows 上构建一个利用 Microsoft Graph SDK 显示用户数据的跨平台应用来实践 .NET MAUI。
在本教程中,你将了解如何执行以下操作:
- 为 .NET MAUI 开发设置环境并创建 .NET MAUI 项目
- 在 Azure 中注册客户端应用
- 与 Azure 标识 和 Microsoft Graph SDK 集成
- 更新用户界面以显示 Microsoft Graph 中的用户信息
先决条件
- 具有活动订阅的 Azure 帐户。 免费创建帐户。
- .NET MAUI 安装要求。
- 如果你不熟悉 Windows 上的 .NET MAUI,应从 生成第一个适用于 Windows 的 .NET MAUI 应用 教程开始。
设置环境
如果尚未为 .NET MAUI 开发设置环境,请按照 Windows 上的 .NET MAUI 入门步骤进行操作。
创建 .NET MAUI 项目
注意
如果已熟悉设置 .NET MAUI 项目,可以跳到 在 Azure 中注册客户端 部分。
启动 Visual Studio,然后在“开始”窗口中单击“ 创建新项目 ”以创建新项目:
在 “创建新项目 ”窗口中,在“所有项目类型”下拉列表中选择 “MAUI ”,选择 “.NET MAUI 应用 ”模板,然后单击“ 下一步 ”按钮:
在 “配置新项目 ”窗口中,为项目指定一个名称,为其选择一个位置,然后单击“ 下一步 ”按钮:
在“ 其他信息 ”窗口中,单击“ 创建 ”按钮:
等待创建项目并还原其依赖项:
在 Visual Studio 工具栏中,按 “Windows 计算机 ”按钮生成并运行应用。 单击 “单击我” 按钮,并验证按钮内容是否随单击次数一起更新。
现在,你已验证 Windows 上的 .NET MAUI 应用正在按预期工作,我们可以集成 Graph SDK。 在下一部分中,你将添加对 Microsoft Graph 进行身份验证和调用所需的包。
在 Azure 中注册客户端
若要从 Microsoft Graph 读取用户数据,需要在 Azure 中 注册 授予应用的 User.Read 范围。 若要注册应用程序,请执行以下步骤:
登录到 Azure 门户。
如果有权访问多个租户,请使用顶部菜单中的 “目录 + 订阅 ”筛选器切换到要在其中注册应用程序的租户。
搜索并选择“Azure Active Directory” 。
在“管理”下,选择“应用注册”>“新建注册”。
输入应用程序的名称(例如 Win-App-calling-MsGraph
)。 应用的用户可能会看到此名称,你稍后可对其进行更改。
在“支持的帐户类型”部分,选择“任何组织目录中的帐户和个人 Microsoft 帐户(例如 Skype、Xbox、Outlook.com)”。
选择“注册”以创建应用程序。
复制并保存 应用程序 (客户端) ID 和 目录 (租户的) ID 值供以后使用。 我们将在下一部分的 GraphService 类中存储这些值。
在“管理”下,选择“身份验证”。
选择“ 添加平台 > 移动和桌面应用程序”。
在“重定向 URI”部分中,选择并在“https://login.microsoftonline.com/common/oauth2/nativeclient
自定义重定向 URI”中添加 https://localhost
。
选择“配置” 。
在“管理”下选择“API 权限” 。
如果“配置的权限”下不存在 Microsoft Graph User.Read 权限,请选择“添加权限”。 在 “请求 API 权限 ”屏幕中,选择“ Microsoft Graph > 应用程序权限 ”并搜索 “User.Read”。 展开 “用户”,选择“ User.Read”,然后单击“ 添加权限”。
集成 Graph SDK 和 Azure 标识
现在,在 Windows 上运行 .NET MAUI 应用并在 Azure 中配置了应用注册,接下来将几个 NuGet 包添加到项目,以便与 Azure 标识和 Microsoft Graph 集成。
右键单击解决方案资源管理器中的项目,然后从上下文菜单中选择“管理 NuGet 包...”。
在 “NuGet 包管理器 ”窗口中,选择“ 浏览 ”选项卡并搜索 Azure.Identity:
单击“安装”,将 Azure.Identity 包的最新稳定版本添加到项目。
接下来,搜索 Microsoft.Graph:
单击“安装”,将 Microsoft.Graph 包的最新稳定版本添加到项目。
在新包完成安装后,关闭 “NuGet 包管理器 ”窗口。
再次右键单击该项目,然后选择“ 添加 | 上下文菜单中的类。
在出现的 “添加新项” 窗口中,为类 GraphService
命名,然后单击“ 添加”:
向 类添加四个私有成员 GraphService
,将自己的 客户端 ID 和 租户 ID 值替换为占位符文本:
private readonly string[] _scopes = new[] { "User.Read" };
private const string TenantId = "<add your tenant id here>";
private const string ClientId = "<add your client id here>";
private GraphServiceClient _client;
将 方法 Initialize()
添加到 GraphService
,该方法将从构造函数调用。 初始化代码将使用 类进行身份验证 InteractiveBrowserCredential
。 身份验证成功后,身份验证令牌将由凭据类以及请求的范围 (User.Read
) 提供给 GraphServiceClient
。
public GraphService()
{
Initialize();
}
private void Initialize()
{
// assume Windows for this sample
if (OperatingSystem.IsWindows())
{
var options = new InteractiveBrowserCredentialOptions
{
TenantId = TenantId,
ClientId = ClientId,
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
RedirectUri = new Uri("https://localhost"),
};
InteractiveBrowserCredential interactiveCredential = new(options);
_client = new GraphServiceClient(interactiveCredential, _scopes);
}
else
{
// TODO: Add iOS/Android support
}
}
注意
“Initialize () ”方法目前仅支持 Windows。 在 iOS 和 Android 上进行身份验证需要不同的 NuGet 包 (Microsoft.Identity.Client) 和其他一些步骤。 若要详细了解移动身份验证,请参阅 配置本机客户端应用程序。
添加名为 GetMyDetailsAsync()
的公共异步方法以返回 User
经过身份验证的用户的对象:
public async Task<User> GetMyDetailsAsync()
{
try
{
return await _client.Me.GetAsync();
}
catch (Exception ex)
{
Console.WriteLine($"Error loading user details: {ex}");
return null;
}
}
需要两个 using
语句来编译添加到 GraphService
的新代码:
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
在 MainPage.xaml 中,将 添加到 x:Name
Hello, World! 标签:
<Label
x:Name="HelloLabel"
Text="Hello, World!"
SemanticProperties.HeadingLevel="Level1"
FontSize="32"
HorizontalOptions="Center" />
将新按钮添加到页面的后面, CounterBtn
以从 Graph 获取用户信息:
<Button
x:Name="GetUserInfoBtn"
Text="Load User Info"
SemanticProperties.Hint="Loads user information from Microsoft Graph"
Clicked="GetUserInfoBtn_Clicked"
HorizontalOptions="Center" />
在 MainPage.xaml.cs 中,将私有变量添加到 和 GraphService
User
:
private GraphService graphService;
private User user;
为Clicked
添加到 MainPage.xaml 上的 的事件GetUserInfoButton
添加事件处理程序。 事件处理程序将创建 一个 实例 GraphService
(如果 为 null)并调用 来提取用户数据。 的文本 HelloLabel
将更新为向用户打招呼,并显示 DisplayName
Microsoft Graph 中的 属性:
private async void GetUserInfoBtn_Clicked(object sender, EventArgs e)
{
if (graphService == null)
{
graphService = new GraphService();
}
user = await graphService.GetMyDetailsAsync();
HelloLabel.Text = $"Hello, {user.DisplayName}!";
}
运行应用并单击“ 加载用户信息” 按钮:
出现“ 登录到帐户” 窗口时,选择现有帐户或单击“ 使用其他帐户”:
如果选择了其他帐户,请输入该帐户的电子邮件地址和密码并登录。
身份验证完成后,你将在应用上看到用户的 DisplayName :
更新用户界面以显示用户信息
现在, GraphService
正在返回用户信息,让我们更新用户界面以显示一些额外的用户配置文件信息。
在 MainPage.xaml 中,首先更新 的内容 VerticalStackLayout
,删除现有的欢迎标签和 Image
控件,并添加四个新标签以显示用户信息。 每个将更新的标签都命名为 ,我们已提供一些占位符文本,直到从 Graph 查询加载数据。 VerticalStackLayout
的内容现在应如下所示:
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<Label
x:Name="HelloLabel"
Text="Hello, World!"
SemanticProperties.Description="Displays a welcome message for the user"
SemanticProperties.HeadingLevel="Level1"
FontSize="32"
HorizontalOptions="Center" />
<Button
x:Name="CounterBtn"
Text="Click me"
SemanticProperties.Hint="Counts the number of times you click"
Clicked="CounterBtn_Clicked"
HorizontalOptions="Center" />
<Button
Text="Load User Info"
SemanticProperties.Hint="Loads user information from Microsoft Graph"
Clicked="GetUserInfoBtn_Clicked"
HorizontalOptions="Center" />
<Label
x:Name="DisplayNameLabel"
Text="Display name"
SemanticProperties.Description="Displays the user's display name from Microsoft Graph."
SemanticProperties.HeadingLevel="Level2"
FontSize="18"
HorizontalOptions="Center" />
<Label
x:Name="UserFirstNameLabel"
Text="First name"
SemanticProperties.Description="Displays the user's first name info from Microsoft Graph"
SemanticProperties.HeadingLevel="Level2"
FontSize="18"
HorizontalOptions="Center" />
<Label
x:Name="UserLastNameLabel"
Text="Last name"
SemanticProperties.Description="Displays the user's last name from Microsoft Graph"
SemanticProperties.HeadingLevel="Level2"
FontSize="18"
HorizontalOptions="Center" />
<Label
x:Name="UserPrincipalNameLabel"
Text="User Principal Name"
SemanticProperties.Description="Displays the user principal name from Microsoft Graph"
SemanticProperties.HeadingLevel="Level2"
FontSize="18"
HorizontalOptions="Center" />
</VerticalStackLayout>
最后,在 MainPage.xaml.cs 中,使用 Graph User 对象的属性在事件处理程序中使用 GetUserInfoBtn_Clicked
新属性的值更新 UI 元素:
private async void GetUserInfoBtn_Clicked(object sender, EventArgs e)
{
if (graphService == null)
{
graphService = new GraphService();
}
user = await graphService.GetMyDetailsAsync();
HelloLabel.Text = $"Hello, {user.DisplayName}!";
DisplayNameLabel.Text = user.DisplayName;
UserFirstNameLabel.Text = user.GivenName;
UserLastNameLabel.Text = user.Surname;
UserPrincipalNameLabel.Text = user.UserPrincipalName;
}
再次运行应用,然后单击“ 加载用户信息” 按钮。 在进行身份验证后,你应会看到应用中显示的用户信息:
若要了解如何在 .NET MAUI 应用中安装和开始使用 Microsoft Graph SDK,请参阅 安装 Microsoft Graph .NET SDK。
后续步骤
转到下一篇文章,了解如何…
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈