c# - People API does not return email address

2019-08-26 21:07发布

问题:

I am trying to get the email address and name of the logged-in user. I can see the name of the user but the email address shows null. Here is the code I have written to retrieve both the values:

using Google.Apis.Auth.OAuth2;
using Google.Apis.People.v1;
using System.Net;
using System.Threading;
using Google.Apis.Services;
using Google.Apis.People.v1.Data;


UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
 new ClientSecrets
               {
                   ClientId = "jfms2vr52dm9eghchabasa5.apps.googleusercontent.com",
                   ClientSecret = "xxxxxxxxxxxx"
               },
               new[] { "profile", "https://www.googleapis.com/auth/contacts.readonly", "https://www.googleapis.com/auth/user.birthday.read", "https://www.googleapis.com/auth/userinfo.email" },
               "me",
               CancellationToken.None).Result;

        // Create the service.
        var service = new PeopleService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "M_Test1",
        });

        PeopleResource.GetRequest peopleRequest = service.People.Get("people/me");          
        peopleRequest.RequestMaskIncludeField = "person.names,person.emailAddresses,person.birthdays";
        Person profile = peopleRequest.Execute();

回答1:

It looks like you have changed your scopes. In order to see the email address the user must have granted you access to the email scope. The credentails for the user who is logged in are stored in %appdata% under the name me which is the name you gave it in the code below.

    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
 new ClientSecrets
               {
                   ClientId = "jfms2vr52dm9eghchabasa5.apps.googleusercontent.com",
                   ClientSecret = "xxxxxxxxxxxx"
               },
               new[] { "profile", "https://www.googleapis.com/auth/contacts.readonly", "https://www.googleapis.com/auth/user.birthday.read", "https://www.googleapis.com/auth/userinfo.email" },
               "me",  // change this to reset login
               CancellationToken.None).Result;

This is just a string denoting the user. You can change it to anything else and it will prompt you to login again. Or you can just delete the file in %appdata%