[ Office 365 开发系列 ] Graph Service
前言
本文完全原创,转载请说明出处,希望对大家有用。
通过[ Office 365 开发系列 ] 开发模式分析和[ Office 365 开发系列 ] 身份认证两篇内容的了解,我们可以开始使用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实现,如下所示:
<!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>
(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
OK,只要这两段代码就可以了,首先要运行起来,如果不知道如何注册应用到AAD,请参考[ Office 365 开发系列 ] 身份认证
上述代码的逻辑是通过调用graph api中的messages资源,获取用户邮件信息。
二、 使用Graph服务类调用
如果我们使用后台服务的方式为用户提供服务,则需要使用HttpWebRequest来发起rest请求,如果每个都由自己处理当然是可以,不过微软已经为我们提供了调用封装,那还是省点时间去做业务逻辑吧。
以MVC为例,我们为用户提供一个获取个人邮件的方法,示例代码基于Office Dev Center创建:
@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>
显示页面
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", "");
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
这里要注意,使用GraphServiceClient需要引用Microsoft.Graph程序集。
结束语
以上为Graph API的介绍,请继续关注后续博客。
[ Office 365 开发系列 ] Graph Service的更多相关文章
- [ Office 365 开发系列 ] 身份认证
前言 本文完全原创,转载请说明出处,希望对大家有用. 通常我们在开发一个应用时,需要考虑用户身份认证及授权,Office 365使用AAD(Azure Active Directory)作为其认证机构 ...
- [ Office 365 开发系列 ] 开发模式分析
前言 本文完全原创,转载请说明出处,希望对大家有用. 在正式开发Office 365应用前,我们先了解一下Office 365的开发模式,根据不同的应用场景,我们选择最适合的开发模式. 阅读目录 Of ...
- [ Office 365 开发系列 ] 前言
前言 本人从接触Microsoft SharePoint Server 2007到目前为止,已经在微软SharePoint的路上已经走了好几年,基于SharePoint平台的特殊性,对微软产品线都有了 ...
- Office 365开发概述及生态环境介绍(一)
原文于2017年3月13日首发于LinkedIn,请参考这个链接 离上一篇文章,很快又过去了两星期的时间.今天抓紧晚上的时间,开始了Office 365开发系列文章的第一篇,我会帮助大家回顾一下过去O ...
- Office 365 开发概览系列文章和教程
Office 365 开发概览系列文章和教程 原文于2017年2月26日首发于LinkedIn,请参考链接 引子 之前我在Office 365技术社群(O萌)中跟大家提到,3月初适逢Visual St ...
- Office 365开发概述及生态环境介绍(二)
本文于2017年3月19日首发于LinkedIn,原文链接在这里 在上一篇 文章,我给大家回顾了Office发展过来的一些主要的版本(XP,2003,2007,2013等),以及在Office客户端中 ...
- 《Office 365 开发入门指南》公开邀请试读,欢迎反馈
终于等来了这一天,可以为我的这本新书画上一个句号.我记得是在今年的2月份从西雅图回来之后,就萌发了要为中国的Office 365开发人员写一些东西并最终能帮到更多中国用户的想法,而从2月26日正式写下 ...
- 拥抱开源,Office 365开发迎来新时代
前言 作为全球最大的开放源代码托管平台,Github在上周迎来了它的十岁生日.自从2008年正式上线以来,Github上面汇聚了数以千万计的开发人员和各种项目,它几乎成为了开源的代名词和风向标,各大软 ...
- Office 365 开发入门
<Office 365 开发入门指南>公开邀请试读,欢迎反馈 终于等来了这一天,可以为我的这本新书画上一个句号.我记得是在今年的2月份从西雅图回来之后,就萌发了要为中国的Office 36 ...
随机推荐
- blender, 创建多边形面片
按a键清除所有选择,进入Edit Mode,选vertex select方式.然后按住control,使用MLB连续画多个顶点,形成一个多边形,如图所示: 然后同时选中两个端点,点Make Edge/ ...
- 从 "org.apache.hadoop.security.AccessControlException:Permission denied: user=..." 看Hadoop 的用户登陆认证
假设远程提交任务给Hadoop 可能会遇到 "org.apache.hadoop.security.AccessControlException:Permission denied: use ...
- Unity和安卓互调
Unity调安卓 AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); And ...
- makefile之override
override指示符 通常在执行 make 时,如果通过命令行定义了一个变量,那么它将替代在 Makefile中出现的同名变量的定义. 就是说,对于一个在 Makefile 中使用常规方式(使用&q ...
- UltraISO制作启动盘及提取U盘为ISO镜像
我们先来说下UltraISO这个工具,中文名也叫软碟通,他是一个无需量产你的U盘就可以把U盘做成启动盘的工具,当然了,这么强大的工具肯定不是免费版的,对,他是共享的:但是你可以下载特别版嘛..网上到处 ...
- nyoj 15 括号匹配(2)
括号匹配(二) 时间限制:1000 ms | 内存限制:65535 KB 难度:6 描述 给你一个字符串,里面只包含"(",")","[" ...
- angularJs 页面定时刷新
angularJs 页面定时刷新 页面定时刷新并在页面离开时停止自动刷新 var autoRefresh; //自动刷新 autoRefresh = $interval($scope.loadData ...
- widnows 使用WIN32 APi 实现修改另一打开程序的窗口显示方式
1.GUI点击打开一个程序那边做一个判断. hwnd = 获取目标程序窗口句柄: if(hwnd == NULL /*不存在目标程序窗口句柄*/){ 创建进程,打开目标程序: } else{ ...
- mysql 位运算
& 与运算 | 或运算 ^ 异或运算 或者 你也可以将 与运算理解为 + 法 例如 1|2 = 3 (1+2 = 3)1|2|4 = 7 (1+2+4 = 7) 将 异或运算理解为 - ...
- Odoo ParseError:"decoder jpeg not available" while parsing....
The reason causing this problem is the plugin PIL install error to solve this problem,try this: 1. c ...