如何从IOneDriveClient
获取用户名或电子邮件?
验证
string[] scopes = { "onedrive.readwrite" };
IOneDriveClient OneDriveClient = OneDriveClientExtensions.GetUniversalClient(scopes);
await OneDriveClient.AuthenticateAsync();
答案 0 :(得分:5)
我们无法直接从IOneDriveClient
获取用户名或电子邮件。但是从表格IOneDriveClient
我们可以获得AccessToken
。当我们有AccessToken
时,我们可以使用Live Connect Representational State Transfer(REST)API来检索用户名。
用于请求有关已登录用户的信息的REST API是:
GET https://apis.live.net/v5.0/me?access_token=ACCESS_TOKEN
有关详细信息,请参阅Requesting info using REST。
因此,在应用程序中,我们可以使用以下代码来获取用户的显示名称:
string[] scopes = new string[] { "onedrive.readwrite" };
var client = OneDriveClientExtensions.GetUniversalClient(scopes) as OneDriveClient;
await client.AuthenticateAsync();
//get the access_token
var AccessToken = client.AuthenticationProvider.CurrentAccountSession.AccessToken;
//REST API to request info about the signed-in user
var uri = new Uri($"https://apis.live.net/v5.0/me?access_token={AccessToken}");
var httpClient = new System.Net.Http.HttpClient();
var result = await httpClient.GetAsync(uri);
//user info returnd as JSON
string jsonUserInfo = await result.Content.ReadAsStringAsync();
if (jsonUserInfo != null)
{
var json = Newtonsoft.Json.Linq.JObject.Parse(jsonUserInfo);
string username = json["name"].ToString();
}
要获取用户的电子邮件,我们需要在wl.emails
中添加scopes
范围。 wl.emails scope启用对用户电子邮件地址的读取权限。代码可能如下:
string[] scopes = new string[] { "onedrive.readwrite", "wl.emails" };
var client = OneDriveClientExtensions.GetUniversalClient(scopes) as OneDriveClient;
await client.AuthenticateAsync();
//get the access_token
var AccessToken = client.AuthenticationProvider.CurrentAccountSession.AccessToken;
//REST API to request info about the signed-in user
var uri = new Uri($"https://apis.live.net/v5.0/me?access_token={AccessToken}");
var httpClient = new System.Net.Http.HttpClient();
var result = await httpClient.GetAsync(uri);
//user info returnd as JSON
string jsonUserInfo = await result.Content.ReadAsStringAsync();
if (jsonUserInfo != null)
{
var json = Newtonsoft.Json.Linq.JObject.Parse(jsonUserInfo);
string username = json["name"].ToString();
string email = json["emails"]["account"].ToString();
}