我們可以開始使用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)容做一個簡要的介紹。 終結(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),如下所示: - <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>Graph API Demo</title>
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
- </head>
- <body role="document">
- <table class="table table-striped table-bordered table-condensed table-hover">
- <thead>
- <tr>
- <th>接收時間</th>
- <th>郵件主題</th>
- </tr>
- </thead>
- <tbody class="data-container">
- <tr>
- <td class="view-data-type"></td>
- <td class="view-data-name"></td>
- </tr>
- </tbody>
- </table>
-
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
- <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.js"></script>
- <script src="App/Scripts/demo.js"></script>
- </body>
- </html>
復(fù)制代碼- (function () {
- var baseEndpoint = 'https://graph.microsoft.com';
- window.config = {
- tenant: 'bluepoint360.onmicrosoft.com',
- clientId: '08d87e99-f2dd-4b4d-b402-bcf7a5ea43ca',
- postLogoutRedirectUri: window.location.origin,
- cacheLocation: 'localStorage', // enable this for IE, as sessionStorage does not work for localhost.
- };
- var authContext = new AuthenticationContext(config);
- var $dataContainer = $(".data-container");
- authContext.acquireToken(baseEndpoint, function (error, token) {
- if (error || !token) {
- console.log('ADAL error occurred: ' + error);
- return;
- }
- $.ajax({
- type: "GET",
- url: baseEndpoint + "/v1.0/me/messages",
- headers: {
- 'Authorization': 'Bearer ' + token,
- }
- }).done(function (response) {
- var $template = $(".data-container");
- var output = '';
- response.value.forEach(function (item) {
- var $entry = $template;
- $entry.find(".view-data-type").html(item.receivedDateTime);
- $entry.find(".view-data-name").html(item.subject);
- output += $entry.html();
- });
- $dataContainer.html(output);
- });
- });
- }());
- demo.js
復(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)建: - @model List<Tuple<string,string>>
- <table class="table">
- <tr>
- <th>接收時間</th>
- <th>郵件主題</th>
- </tr>
- @foreach (var item in Model)
- {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.Item1)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Item2)
- </td>
- </tr>
- }
- </table>
- 顯示頁面
復(fù)制代碼- public class DefaultController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- public async Task<ActionResult> RetrieveUserEmails()
- {
- List<Tuple<string, string>> mailResults = new List<Tuple<string, string>>();
- try
- {
- GraphServiceClient exClient = new GraphServiceClient(new GraphAuthentication());
- QueryOption topcount = new QueryOption("$top", "10");
- var _Results = await exClient.Me.Messages.Request(new[] { topcount }).GetAsync();
- var mails = _Results.CurrentPage;
- foreach (var mail in mails)
- {
- mailResults.Add(new Tuple<string, string>(mail.ReceivedDateTime.ToString(), mail.Subject));
- }
- }
- catch (Exception ex)
- {
- return View(ex.Message);
- }
- return View(mailResults);
- }
- }
- public class GraphAuthentication : IAuthenticationProvider
- {
- public async Task AuthenticateRequestAsync(System.Net.Http.HttpRequestMessage request)
- {
- AuthenticationResult authResult = null;
- var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
- var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
- var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
- AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", "https://login.microsoftonline.com", tenantId), new ADALTokenCache(signInUserId));
- try
- {
- authResult = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", new ClientCredential("your client ID", "your client secret"), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
- request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
- }
- catch (AdalException ex)
- {
- if (ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
- {
- authContext.TokenCache.Clear();
- }
- }
- }
- }
- MVC Controller
復(fù)制代碼
這里要注意,使用GraphServiceClient需要引用Microsoft.Graph程序集。
本文轉(zhuǎn)載自博客園:任澤華Ryan《[ Office 365 開發(fā)系列 ] Graph Service》
|