GoogleWebAuthorizationBroker.AuthorizeAsync会引发错误

时间:2015-09-02 10:21:33

标签: c#

我正在尝试创建并运行此link中给出的示例项目。 这是代码:

namespace GmailQuickstart
{
    class Program
    {
        static string[] Scopes = { GmailService.Scope.GmailReadonly };
        static string ApplicationName = "Gmail API Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

            // Define parameters of request.
            UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");

            // List labels.
            IList<Label> labels= request.Execute().Labels;
            Console.WriteLine("Labels:");
            if (labels != null && labels.Count > 0)
            {
                foreach (var labelItem in labels)
                {
                    Console.WriteLine("{0}", labelItem.Name);
                }
            }
            else
            {
                Console.WriteLine("No labels found.");
            }
            Console.Read();

        }
    }
}

在我完成了谷歌文档中所述的所有内容后,包括为我的应用程序/产品发布了secrets.json文件,我运行了它。
它失败并出现异常,包含“提供了无效参数”内部异常 给了新的api凭证等,我用新的acocunt重试了所有内容,但仍然发生了同样的错误。我做错了什么?

1 个答案:

答案 0 :(得分:0)

试试这个

ClientSecrets secrets = new ClientSecrets()
{
    ClientId = CLIENT_ID,
    ClientSecret = CLIENT_SECRET
};

var token = new TokenResponse { RefreshToken = REFRESH_TOKEN }; 
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
    new GoogleAuthorizationCodeFlow.Initializer 
    {
        ClientSecrets = secrets
    }), 
    "user", 
    token);

var service = new GmailService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credentials,
    ApplicationName = "ApplicationName"
});