如何从onedriveclient sdk c#获取用户名或电子邮件

How to get username or email from onedriveclient sdk c#

如何从 IOneDriveClient 获取用户名或电子邮件?

身份验证:

string[] scopes = { "onedrive.readwrite" };
IOneDriveClient OneDriveClient = OneDriveClientExtensions.GetUniversalClient(scopes);
await OneDriveClient.AuthenticateAsync();

我们无法直接从 IOneDriveClient 获取用户名或电子邮件。但是从 IOneDriveClient 我们可以得到 AccessToken。当我们有 AccessToken 时,我们可以将它与 Live Connect Representational State Transfer (REST) API 一起使用来检索用户名。

请求 signed-in 用户信息的 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();
}

要获取用户的电子邮件,我们需要在 scopes 中添加 wl.emails 范围。 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();
}