我按照本页提到的说明编写代码:
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'至 ' Google.Apis.Services.IClientService'
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
您需要使用Oauth访问Google日历。您的方式仅适用于Public 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;
}
}