SharePoint REST API:通过用户名获取用户 ID





5.00/5 (4投票s)
以下技巧将帮助开发人员使用 SharePoint REST API 通过帐户名检索用户 ID。
引言
这不是一篇文章,而是一个小技巧。在某些情况下,需要获取 SharePoint 中特定站点用户的 UserId
。此技巧可以通过传递登录名来获取站点用户的 UserId
,这可能会有所帮助。SharePoint 提供了开箱即用的 REST API 来获取站点用户,但是,使用登录名格式(该格式取决于 SharePoint 环境),会变得有些棘手。
获取站点用户的 REST 端点是:http://<站点 URL>/_api/web/siteusers(@v)?@v='<传递登录名>'
Using the Code
以下代码可以包含在您的页面中,以获取给定站点用户的 UserId
。
//
// Include JQuery reference
// ... script continues ...
/// username should be passed as 'domain\username'
function GetUserId(userName) {
/// change this prefix according to the environment.
/// In below sample, windows authentication is considered.
var prefix = "i:0#.w|";
/// get the site url
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
/// add prefix, this needs to be changed based on scenario
var accountName = prefix + userName;
/// make an ajax call to get the site user
$.ajax({
url: siteUrl + "/_api/web/siteusers(@v)?@v='" +
encodeURIComponent(accountName) + "'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
///popup user id received from site users.
alert("Received UserId" + data.d.Id);
alert(JSON.stringify(data));
},
error: function (data) {
console.log(JSON.stringify(data));
}
});
}
- 对于 SharePoint Online 或本地表单身份验证,请使用以下登录名格式
i: 0#.f|membership|user@domain.com
- 对于 SharePoint 2013 本地 Windows 身份验证,请使用以下登录名格式
i: 0#.w|domain\user
- 对于 SharePoint 2013 本地基于 SAML 的身份验证,请使用以下登录名格式
?i: 05:t|adfs with roles|user@domain.com
有关登录名示例和更多信息,请参阅 MSDN 链接中的“表 1 登录名格式”:http://msdn.microsoft.com/en-us/library/office/dn531432(v=office.15).aspx。
关注点
在未附加登录名格式前缀的情况下,SharePoint 会返回错误 HTTP 500,因此根据环境识别合适的登录格式并将其设置为登录名前缀非常重要。
参考资料:用户、组和角色,REST API 参考和示例
http://msdn.microsoft.com/en-us/library/office/dn531432(v=office.15).aspx