无法创建 Google.Apis.Services.BaseClientService 的实例
本文关键字:BaseClientService 实例 Services Apis 创建 Google | 更新日期: 2023-09-27 18:33:27
我正在按照本页提到的说明编写代码:
https://developers.google.com/api-client-library/dotnet/get_started
按照上述资源中的以下代码行:-
// Create the service.
var service = new DiscoveryService(new BaseClientService.Initializer
{
ApplicationName = "Discovery Sample",
APIKey="[YOUR_API_KEY_HERE]",
});
我编写了以下代码来访问Google日历条目:-
CalendarListResource r = new CalendarListResource(new BaseClientService.Initializer
{
ApiKey = "sdfsdfsdf",
ApplicationName = "Expenses"
});
但是,我收到以下错误:-
无法从 转换'Google.Apis.Services.BaseClientService.Initializer' to'Google.Apis.Services.IClientService'
谁能帮我解决这个问题?
您需要使用 Oauth 才能访问 Google 日历。 执行此操作的方式仅适用于公共 API。
这是让Oauth2与Google日历一起使用的快速示例
/// <summary>
/// Authenticate to Google Using Oauth2
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
/// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
/// <param name="userName">A string used to identify a user.</param>
/// <returns></returns>
public static CalendarService AuthenticateOauth(string clientId, string clientSecret, string userName)
{
string[] scopes = new string[] {
CalendarService.Scope.Calendar , // Manage your calendars
CalendarService.Scope.CalendarReadonly // View your Calendars
};
try
{
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, userName
, CancellationToken.None
, new FileDataStore("Daimto.GoogleCalendar.Auth.Store")).Result;
CalendarService service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Sample",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
}