MSGraphMailbag - Blazor web 程序集和 Microsoft Graph、Azure Functions 的三层架构

本篇文章演示将 ASP.Net Core Blazor Web 程序集作为前端、Microsoft Azure Functions 作为中间业务逻辑层、Microsoft Graph 作为数据层的三层架构,即如何使用 Microsoft Graph 在 Blazor Web 程序集上展示 Microsoft 365 的数据和服务进而进行交互。

概述

本篇文章介绍的完整代码仓库地址
https://github.com/fabianwilliams/blazorwithgraphonazurefunct

演示分为3个主要步骤:

  1. 前提仍然是需要在应用程序注册中注册一个应用用来访问 Microsoft 365 的数据。
    =>旧文章传送门<=
  2. 在 Visual Studio 中创建一个通过 Microsoft Graph 访问 Microsoft 365 数据的 Azure Function。
    快速入门:使用 Visual Studio 在 Azure 中创建第一个函数
  3. 创建一个 Blazor Web 程序集应用来展示数据。
    Blazor 快速入门

应用程序注册

演示要实现的功能为从 Microsoft 365 租户返回用户列表和返回第一个用户。

要实现它们我们需要调用 Microsoft Graph 的获取用户列表终结点

具体创建过程请参考上面的传送门作为参考。
在这里插入图片描述
在这里插入图片描述

创建一个 Azure Function

这个部分的主要步骤有:

  1. 安装恰当的 Microsoft Graph SDK,比如.NET SDK,具体要看使用的是什么语言,还可以是Java、JavaScript、PHP、Ruby、PowerShell等。
  2. 选择合适的身份验证提供程序
  3. 创建 Graph Client
  4. 通过 Graph Client 请求相应的数据。
  5. 处理返回的结果

接下来我们创建 Azure Function。

首先创建一个静态方法用于返回 Graph Client

private static GraphServiceClient GetAuthenticatedGrahClient()
{
    
    
    //The below comment block is how you should go about securing your configurable keys etc. as it will allow you to 
    // send them to Azure API settings upon publish as well as set them up for KeyValult.
    var clientId = Environment.GetEnvironmentVariable("AzureADAppClientId", EnvironmentVariableTarget.Process);
    var tenantID = Environment.GetEnvironmentVariable("AzureADAppTenantId", EnvironmentVariableTarget.Process);
    var clientSecret = Environment.GetEnvironmentVariable("AzureADAppClientSecret", EnvironmentVariableTarget.Process);

    // Build a client application.
    IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
        .Create(clientId)
        .WithTenantId(tenantID)
        .WithClientSecret(clientSecret)
        .Build();
    ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);
    GraphServiceClient graphClient = new GraphServiceClient(authenticationProvider);

    return graphClient;
}

下面的代码片段展示获取用户的 Azure Function

[FunctionName("GetAllUsers")]
public static async Task<IActionResult> GetAllUsersFromGraph(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
    ILogger log)
{
    
    
    List<FabsterUser> ful = new List<FabsterUser>();

    GraphServiceClient graphClient = GetAuthenticatedGrahClient();
    List<QueryOption> options = new List<QueryOption>
    {
    
    
        new QueryOption("$select", "displayName,givenName,mail")
    };

    var graphResult = graphClient.Users.Request(options).GetAsync().Result;

    List<User> usersList = graphResult.CurrentPage.ToList();

    foreach (User u in usersList)
    {
    
    
        log.LogInformation("Showing: " + u.GivenName + " - " + u.Mail);
    }

    log.LogInformation("Graph SDK Result for All Users");

    string responseMessage = string.IsNullOrEmpty(graphResult.ToString())
        ? "Call to Microsoft Graph on Fabster Tenanat App executed successfully."
        : $"{graphResult}";

    return new OkObjectResult(usersList);
}

关于如何将 Azure Function 发布到 Azure,参考这里

发布之后我们就可以测试它了,可以用浏览器或者PostMan,如下图。
在这里插入图片描述

创建 Blazor Web 应用程序

在这里插入图片描述
创建好项目后,添加两个 RazorComponents 页面 GetTopUser 和 GetAllUsers 并修改 Shared\NavMenu.razor 页面,向其中添加两个导航元素
在这里插入图片描述
GetAllUsers.razor的代码如下

@page "/getallusers"
@inject HttpClient Http

<h1>Get All My Users in my Graph via FabsContoso Tenant</h1>

<p>This component demonstrates fetching data using Microsoft Graph via an Azure Function</p>

@if (message == null)
{
    
    
    <p><em>Loading all graph users...</em></p>
}
else
{
    
    
    <p>@message </p>
}

@functions {
    
    
    string message;

    protected override async Task OnInitializedAsync()
    {
    
    
        //no Try Catch because we are Cowboys :-)
        //message = await Http.GetStringAsync("http://localhost:7071/api/GetUserFromMSGraphOne");
        message = await Http.GetStringAsync("https://fabsgraphmailbagalpha.azurewebsites.net/api/GetAllUsers?code=REDACTED");
    }
}

执行效果如下图
在这里插入图片描述
本篇完

猜你喜欢

转载自blog.csdn.net/FoxDave/article/details/113778680
今日推荐