设为首页收藏本站Access中国

Office中国论坛/Access中国论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

返回列表 发新帖
查看: 1517|回复: 0

[Office插件] [ Office 365 开发系列 ] Graph Service

[复制链接]

点击这里给我发消息

发表于 2018-11-24 16:42:46 | 显示全部楼层 |阅读模式
我们可以开始使用Office 365提供的各项接口开发应用了,接下来会对其提供的主要接口一一分析并通过示例代码为大家讲解接口功能。


Graph API介绍
最近Office 365发布了一项新的功能Delve,此项功能为用户提供了基于人员信息及搜索的发现,有点拗口,其实就是使用Graph API提供的一些列接口,如当前所处的组织、正在处理的文档以及与我相关的事件等等内容,让用户更快的发现与自己相关的内容。Office 365提供这样一个API集合有什么用呢,我们直接使用邮件、文件、AAD的接口也一样可以实现这些内容,事实上我们的确可以这么做,而Graph API是对这些更下层的API进行了封装,让我们不需要再深入了解每一项内容如何存储、如何获取,只需要关注业务本身的需求。下图是Graph API官方的结构图,我借用一下:

从上图所示的内容,我们可以发现Graph API是Office 365作为统一接口为我们提供服务访问的(主页中说:One endpoint to rule them all),我们可以不用了解Users信息是存放在哪里,Graph会帮你找到,我们可以不用了解如何从Outlook中获取邮件,Graph提供现成接口。这么一看,果然功能强大,不过值得注意的是,Graph API接口不是全能的,目前来说还是有一些限制,如对SharePoint Online的操作只局限于个人OneDrive站点。目前最新的版本的1.0,未来Graph API应该会增加更多功能。



Graph API功能
在我们使用者API前,先对API使用方法及提供的内容做一个简要的介绍。
在前面[ Office 365 开发系列 ] 身份认证中我们讲解了如何获取资源Token,本节我们具体到使用Graph API,值得注意的是使用Graph API所用的终结点有国外版和中国版(21v运营)的区别,具体区别如下:
终结点
国际版Office 365
21Vianet Office 365
Azure AD终结点
https://login.microsoftonline.com
https://login.chinacloudapi.cn
Graph资源终结点
https://graph.microsoft.com
https://microsoftgraph.chinacloudapi.cn

Graph API是以Rest服务的方式提供,我们可以使用两种方式调用API,一种是使用JS AJAX方式调用API接口并将token包含在Authorization头中,另外一种是通过微软提供的Graph服务类来获取和解析数据。具体的调用方法我们在下面的Graph API示例分析中来分析,先来了解Graph目前能为我们提供什么。
目前Graph有两个版本(1.0/beta),区别在于我们调用时注意资源地址,API结构为
https://graph.microsoft.com/{version}/{resource}?[odata_query_parameters]
对于Graph所提供的资源内容,请参阅官方文档




Graph API应用示例
为了更好的了解如何调用Graph API,我们以获取用户邮件为例,分别以AJAX和调用Graph服务类方式实现。

一、 使用Ajax调用Graph API
调用由一个html+js实现,如下所示:
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title>Graph API Demo</title>
  5.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  6.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
  7. </head>
  8. <body role="document">
  9.     <table class="table table-striped table-bordered table-condensed table-hover">
  10.         <thead>
  11.             <tr>
  12.                 <th>接收时间</th>
  13.                 <th>邮件主题</th>
  14.             </tr>
  15.         </thead>
  16.         <tbody class="data-container">
  17.             <tr>
  18.                 <td class="view-data-type"></td>
  19.                 <td class="view-data-name"></td>
  20.             </tr>
  21.         </tbody>
  22.     </table>
  23.   
  24.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  25.     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  26.     <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.js"></script>
  27.     <script src="App/Scripts/demo.js"></script>
  28. </body>
  29. </html>
复制代码
  1. (function () {
  2.     var baseEndpoint = 'https://graph.microsoft.com';
  3.     window.config = {
  4.         tenant:  'bluepoint360.onmicrosoft.com',
  5.         clientId: '08d87e99-f2dd-4b4d-b402-bcf7a5ea43ca',
  6.         postLogoutRedirectUri: window.location.origin,
  7.         cacheLocation: 'localStorage', // enable this for IE, as sessionStorage does not work for localhost.
  8.     };
  9.     var authContext = new AuthenticationContext(config);
  10.     var $dataContainer = $(".data-container");
  11.     authContext.acquireToken(baseEndpoint, function (error, token) {
  12.         if (error || !token) {
  13.             console.log('ADAL error occurred: ' + error);
  14.             return;
  15.         }

  16.         $.ajax({
  17.             type: "GET",
  18.             url: baseEndpoint + "/v1.0/me/messages",
  19.             headers: {
  20.                 'Authorization': 'Bearer ' + token,
  21.             }
  22.         }).done(function (response) {
  23.             var $template = $(".data-container");
  24.             var output = '';
  25.             response.value.forEach(function (item) {
  26.                 var $entry = $template;
  27.                 $entry.find(".view-data-type").html(item.receivedDateTime);
  28.                 $entry.find(".view-data-name").html(item.subject);
  29.                 output += $entry.html();
  30.             });
  31.             $dataContainer.html(output);
  32.         });
  33.     });
  34. }());

  35. demo.js
复制代码


OK,只要这两段代码就可以了,首先要运行起来,如果不知道如何注册应用到AAD,请参考[ Office 365 开发系列 ] 身份认证
上述代码的逻辑是通过调用graph api中的messages资源,获取用户邮件信息。

二、 使用Graph服务类调用

如果我们使用后台服务的方式为用户提供服务,则需要使用HttpWebRequest来发起rest请求,如果每个都由自己处理当然是可以,不过微软已经为我们提供了调用封装,那还是省点时间去做业务逻辑吧。
以MVC为例,我们为用户提供一个获取个人邮件的方法,示例代码基于Office Dev Center创建:
  1. @model List<Tuple<string,string>>
  2. <table class="table">
  3.     <tr>
  4.         <th>接收时间</th>
  5.         <th>邮件主题</th>
  6.     </tr>
  7.     @foreach (var item in Model)
  8.     {
  9.         <tr>
  10.             <td>
  11.                 @Html.DisplayFor(modelItem => item.Item1)
  12.             </td>
  13.             <td>
  14.                 @Html.DisplayFor(modelItem => item.Item2)
  15.             </td>
  16.         </tr>
  17.     }
  18. </table>

  19. 显示页面
复制代码
  1. public class DefaultController : Controller
  2.     {
  3.         public ActionResult Index()
  4.         {
  5.             return View();
  6.         }

  7.         public async Task<ActionResult> RetrieveUserEmails()
  8.         {

  9.             List<Tuple<string, string>> mailResults = new List<Tuple<string, string>>();
  10.             try
  11.             {
  12.                 GraphServiceClient exClient = new GraphServiceClient(new GraphAuthentication());
  13.                 QueryOption topcount = new QueryOption("$top", "10");
  14.                 var _Results = await exClient.Me.Messages.Request(new[] { topcount }).GetAsync();

  15.                 var mails = _Results.CurrentPage;
  16.                 foreach (var mail in mails)
  17.                 {
  18.                     mailResults.Add(new Tuple<string, string>(mail.ReceivedDateTime.ToString(), mail.Subject));
  19.                 }
  20.             }
  21.             catch (Exception ex)
  22.             {
  23.                 return View(ex.Message);
  24.             }
  25.             return View(mailResults);
  26.         }
  27.     }

  28.     public class GraphAuthentication : IAuthenticationProvider
  29.     {

  30.         public async Task AuthenticateRequestAsync(System.Net.Http.HttpRequestMessage request)
  31.         {
  32.             AuthenticationResult authResult = null;
  33.             var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
  34.             var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
  35.             var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
  36.             AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", "https://login.microsoftonline.com", tenantId), new ADALTokenCache(signInUserId));
  37.             try
  38.             {

  39.                 authResult = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", new ClientCredential("your client ID", "your client secret"), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
  40.                 request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
  41.             }
  42.             catch (AdalException ex)
  43.             {
  44.                 if (ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
  45.                 {
  46.                    authContext.TokenCache.Clear();
  47.                 }
  48.             }
  49.         }
  50.     }

  51. MVC Controller
复制代码


这里要注意,使用GraphServiceClient需要引用Microsoft.Graph程序集。



本文转载自博客园:任泽华Ryan《[ Office 365 开发系列 ] Graph Service》




您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|站长邮箱|小黑屋|手机版|Office中国/Access中国 ( 粤ICP备10043721号-1 )  

GMT+8, 2024-4-19 02:33 , Processed in 0.121908 second(s), 25 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表