代码之家  ›  专栏  ›  技术社区  ›  Sergio0694

如何使用OneDrive/Graph API检索用户名、电子邮件和图像?

  •  0
  • Sergio0694  · 技术社区  · 7 年前

    我正在开发一个UWP应用程序,我正在考虑从旧的 LiveSDK (已停产,最近一次更新于2015年左右)更新到新的OneDriveSDK(图形API),特别是使用UWP社区工具包服务包及其 APIs .

    就登录和文件/文件夹管理而言,该库似乎很容易使用,但到目前为止,我还没有找到检索用户全名、用户电子邮件和个人资料图片的方法。

    以下是我目前使用LiveSDK(此处简化了代码)执行此操作的代码:

    public static async Task<(String username, String email)> GetUserProfileNameAndEmailAsync(LiveConnectSession session)
    {
        LiveConnectClient connect = new LiveConnectClient(session);
        LiveOperationResult operationResult = await connect.GetAsync("me");
        IDictionary<String, object> results = operationResult.Result;
        String username = results["name"] as String;
        if (!(results["emails"] is IDictionary<string, object> emails)) return default;
        String email = emails["preferred"] as String ?? emails["account"] as String;
        return (username, email);
    }
    
    public static async Task<ImageSource> GetUserProfileImageAsync([NotNull] LiveConnectSession session)
    {
        LiveConnectClient liveClient = new LiveConnectClient(session);
        LiveOperationResult operationResult = await liveClient.GetAsync("me/picture");
        String url = operationResult.Result?["location"] as String;
    
        // The URL points to the raw image data for the user profile picture, just download it
        return default;
    }
    

    我看过导游了 here 我看到似乎有一个替代品可以替代上述所有内容,但我还不能将其与UWP Toolkit服务集成。例如,为了检索用户信息,我尝试了以下方法:

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/");
    await OneDriveService.Instance.Provider.AuthenticationProvider.AuthenticateRequestAsync(request);
    using (HttpResponseMessage response = await OneDriveService.Instance.Provider.HttpProvider.SendAsync(request))    
    {
        String content = await response.Content.ReadAsStringAsync();    
    }
    

    但这失败了,在 SendAsync 呼叫

    注: 我知道有 Graph APIs UWP Toolkit中也有现成的方法来检索用户信息和配置文件图片,但显然您需要office 365订阅才能使用这些API(既作为开发人员,也可能作为用户),所以我想这不是我在这里要找的,因为我一直能够使用普通的OneDrive客户端检索这些信息。

    有没有办法在UWP上做到这一点,或者通过UWP工具包中的某种方法,或者使用其他解决方案?

    谢谢

    编辑: 我重用了示例应用程序中的代码,注册了我的应用程序以获取clientID,并进行了快速测试,但它没有按预期工作,我遇到了以下异常:

    enter image description here

    固定,见下文

    编辑#2: 根据 this 问题,我必须切换到 https://graph.microsoft.com/beta 获取个人资料图片,如 1.0 API版本目前不支持普通MS帐户使用它。从各方面考虑,现在似乎一切正常

    1 回复  |  直到 7 年前
        1
  •  0
  •   Xie Steven    7 年前

    我跟着 MSDN 用于为Microsoft Graph注册我的应用程序的文档。之后,我将获得一个应用程序ID(在API中,它被称为clientId)。

    然后,我用 Microsoft Graph Connect Sample for UWP 使用我的通用MS帐户登录。它工作得很好。我可以得到 username , email

    请注意,如果要成功运行此示例,则需要使用应用程序ID初始化 PublicClientApplication 中的对象 AuthenticationHelper.cs .

    public static PublicClientApplication IdentityClientApp = new PublicClientApplication("your client id");