設(shè)為首頁收藏本站Access中國

Office中國論壇/Access中國論壇

 找回密碼
 注冊

QQ登錄

只需一步,快速開始

返回列表 發(fā)新帖
查看: 2169|回復(fù): 0
打印 上一主題 下一主題

[Office插件] [ Office 365 開發(fā)系列 ] Graph Service

[復(fù)制鏈接]

點擊這里給我發(fā)消息

跳轉(zhuǎn)到指定樓層
1#
發(fā)表于 2018-11-24 16:42:46 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
我們可以開始使用Office 365提供的各項接口開發(fā)應(yīng)用了,接下來會對其提供的主要接口一一分析并通過示例代碼為大家講解接口功能。


Graph API介紹
最近Office 365發(fā)布了一項新的功能Delve,此項功能為用戶提供了基于人員信息及搜索的發(fā)現(xiàn),有點拗口,其實就是使用Graph API提供的一些列接口,如當前所處的組織、正在處理的文檔以及與我相關(guān)的事件等等內(nèi)容,讓用戶更快的發(fā)現(xiàn)與自己相關(guān)的內(nèi)容。Office 365提供這樣一個API集合有什么用呢,我們直接使用郵件、文件、AAD的接口也一樣可以實現(xiàn)這些內(nèi)容,事實上我們的確可以這么做,而Graph API是對這些更下層的API進行了封裝,讓我們不需要再深入了解每一項內(nèi)容如何存儲、如何獲取,只需要關(guān)注業(yè)務(wù)本身的需求。下圖是Graph API官方的結(jié)構(gòu)圖,我借用一下:

從上圖所示的內(nèi)容,我們可以發(fā)現(xiàn)Graph API是Office 365作為統(tǒng)一接口為我們提供服務(wù)訪問的(主頁中說:One endpoint to rule them all),我們可以不用了解Users信息是存放在哪里,Graph會幫你找到,我們可以不用了解如何從Outlook中獲取郵件,Graph提供現(xiàn)成接口。這么一看,果然功能強大,不過值得注意的是,Graph API接口不是全能的,目前來說還是有一些限制,如對SharePoint Online的操作只局限于個人OneDrive站點。目前最新的版本的1.0,未來Graph API應(yīng)該會增加更多功能。



Graph API功能
在我們使用者API前,先對API使用方法及提供的內(nèi)容做一個簡要的介紹。
在前面[ Office 365 開發(fā)系列 ] 身份認證中我們講解了如何獲取資源Token,本節(jié)我們具體到使用Graph API,值得注意的是使用Graph API所用的終結(jié)點有國外版和中國版(21v運營)的區(qū)別,具體區(qū)別如下:
終結(jié)點
國際版Office 365
21Vianet Office 365
Azure AD終結(jié)點
https://login.microsoftonline.com
https://login.chinacloudapi.cn
Graph資源終結(jié)點
https://graph.microsoft.com
https://microsoftgraph.chinacloudapi.cn

Graph API是以Rest服務(wù)的方式提供,我們可以使用兩種方式調(diào)用API,一種是使用JS AJAX方式調(diào)用API接口并將token包含在Authorization頭中,另外一種是通過微軟提供的Graph服務(wù)類來獲取和解析數(shù)據(jù)。具體的調(diào)用方法我們在下面的Graph API示例分析中來分析,先來了解Graph目前能為我們提供什么。
目前Graph有兩個版本(1.0/beta),區(qū)別在于我們調(diào)用時注意資源地址,API結(jié)構(gòu)為
https://graph.microsoft.com/{version}/{resource}?[odata_query_parameters]
對于Graph所提供的資源內(nèi)容,請參閱官方文檔




Graph API應(yīng)用示例
為了更好的了解如何調(diào)用Graph API,我們以獲取用戶郵件為例,分別以AJAX和調(diào)用Graph服務(wù)類方式實現(xiàn)。

一、 使用Ajax調(diào)用Graph API
調(diào)用由一個html+js實現(xiàn),如下所示:
  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>
復(fù)制代碼
  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
復(fù)制代碼


OK,只要這兩段代碼就可以了,首先要運行起來,如果不知道如何注冊應(yīng)用到AAD,請參考[ Office 365 開發(fā)系列 ] 身份認證
上述代碼的邏輯是通過調(diào)用graph api中的messages資源,獲取用戶郵件信息。

二、 使用Graph服務(wù)類調(diào)用

如果我們使用后臺服務(wù)的方式為用戶提供服務(wù),則需要使用HttpWebRequest來發(fā)起rest請求,如果每個都由自己處理當然是可以,不過微軟已經(jīng)為我們提供了調(diào)用封裝,那還是省點時間去做業(yè)務(wù)邏輯吧。
以MVC為例,我們?yōu)橛脩籼峁┮粋獲取個人郵件的方法,示例代碼基于Office Dev Center創(chuàng)建:
  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. 顯示頁面
復(fù)制代碼
  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
復(fù)制代碼


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



本文轉(zhuǎn)載自博客園:任澤華Ryan《[ Office 365 開發(fā)系列 ] Graph Service》




分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 分享分享 分享淘帖 訂閱訂閱
您需要登錄后才可以回帖 登錄 | 注冊

本版積分規(guī)則

QQ|站長郵箱|小黑屋|手機版|Office中國/Access中國 ( 粵ICP備10043721號-1 )  

GMT+8, 2025-7-17 00:44 , Processed in 0.086317 second(s), 24 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回復(fù) 返回頂部 返回列表