如何将.NET Core连接到Google联系人



我想基于数据库编辑谷歌联系人。我已经完成了所有的工作,剩下的就是实现API,但我无法理解如何实现。我已经在Google API仪表板中制作了一个应用程序,并制作了OAuth2.0客户端(我甚至不确定这是否是我所需要的(。

我已经下载了Google程序集,并将它们包含在我的C#控制台应用程序中。

  • 如何从控制台应用程序连接到谷歌联系人
  • 如何在联系人列表中添加和删除条目

答案可以在";已安装的应用程序";部分摘录如下:

使用书籍API的示例代码:

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Books.v1;
using Google.Apis.Books.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
namespace Books.ListMyLibrary
{
/// <summary>
/// Sample which demonstrates how to use the Books API.
/// https://developers.google.com/books/docs/v1/getting_started
/// <summary>
internal class Program
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Books API Sample: List MyLibrary");
Console.WriteLine("================================");
try
{
new Program().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("ERROR: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { BooksService.Scope.Books },
"user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
}
// Create the service.
var service = new BooksService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Books API Sample",
});
var bookshelves = await service.Mylibrary.Bookshelves.List().ExecuteAsync();
...
}
}
}
  • 在这个示例代码中,通过调用GoogleWebAuthorizationBroker.AuthorizeAsync方法创建了一个新的UserCredential实例。这static方法得到以下结果:

    • 客户端机密(或客户端机密的流(
    • 所需的作用域
    • 用户标识符
    • 用于取消操作的取消令牌
    • 可选的数据存储。如果未指定数据存储,则默认为带有默认Google.Apis.Auth文件夹的FileDataStore。这个文件夹是在Environment.SpecialFolder.ApplicationData中创建的
  • 此方法返回的UserCredential被设置为BooksService上的HttpClientInitializer(使用初始值设定项(。像如上所述,UserCredential实现了HTTP客户端初始化器。

  • 注意,在上面的示例代码中,客户端机密信息是从一个文件加载的,但您也可以执行以下操作:


credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "PUT_CLIENT_ID_HERE",
ClientSecret = "PUT_CLIENT_SECRETS_HERE"
},
new[] { BooksService.Scope.Books },
"user",
CancellationToken.None,
new FileDataStore("Books.ListMyLibrary")
);

最新更新