无法从 google 日历同步到我的 .Net Mvc Web App
Cant sync from google calendar to my .Net Mvc Web App
我正在尝试从 google 日历同步到我的 .NET MVC Web 应用程序。
我创建了一个回调方法,Googles Calendar API
会将日历中的新事件发送到该回调方法。但是我没有得到新的 google 日历事件,而是得到了这个 error
:
2021-07-09 12:52:26,982 [ 37] DEBUG DotNetOpenAuth.Messaging - The following required parameters were missing from the DotNetOpenAuth.OAuth2.Messages.AccessTokenFailedResponse message: {error,
}
2021-07-09 12:52:26,997 [ 37] WARN
DotNetOpenAuth.Messaging
Multiple message types seemed to fit the incoming data: {AccessTokenSuccessResponse (2.0), UnauthorizedResponse (2.0), }
2021-07-09 12:52:27,013 [ 37] DEBUG
DotNetOpenAuth.Messaging.Channel
Received AccessTokenSuccessResponse response.
2021-07-09 12:52:27,013 [ 37] INFO
DotNetOpenAuth.Messaging.Channel
Processing incoming AccessTokenSuccessResponse (2.0) message: access_token:
<Access_Token_Number>
token_type: Bearer expires_in: 3599 scope:
https://www.googleapis.com/auth/calendar
2021-07-09 12:52:27,013 [ 37] DEBUG
DotNetOpenAuth.Messaging.Channel
After binding element processing, the received AccessTokenSuccessResponse (2.0) message is: access_token:
<Access_Token_Number>
token_type: Bearer expires_in: 3599 scope:
https://www.googleapis.com/auth/calendar
我该如何处理?
编辑(添加代码)
public void PushNotificationCallback()
{
try
{
var header = Request.Headers;
NotificationResponse notification = new NotificationResponse(header["X-Goog-Channel-Expiration"], header["X-Goog-Channel-Id"], header["X-Goog-Message-Number"], header["X-Goog-Resource-Id"], header["X-Goog-Resource-State"], header["X-Goog-Channel-Token"], header["X-Goog-Resource-Uri"]);
therapistCalendarEntryController.PushNotificationCallback (notification);
}
catch (Exception e)
{
...
}
}
并在控制器动作中
public void PushNotificationCallback(NotificationResponse response)
{
if (!string.IsNullOrEmpty(response?.HTTP_X_GOOG_CHANNEL_TOKEN)) surrounded with if
{
var TherpistRepisitoryCallback = TherapistRepository ?? (Global.IoC.TryResolve<IRepository<Therapist>>());
var therapistId = new Guid(response.HTTP_X_GOOG_CHANNEL_TOKEN);
var therapistCall = TherpistRepisitoryCallback.Get(therapistId);
if (therapistCall != null)
{
SyncGoogleCalendarEvents(therapistCall, null, true);
}
}
}
public void SyncGoogleCalendarEvents(Therapist therapist, string pagingToken, bool syncAllEvents)
{
var TherpistRepisitoryCallback = TherapistRepository ?? (Global.IoC.TryResolve<IRepository<Therapist>>());
var TherapistCalendarEntryRepositoryCallback = TherapistCalendarEntryRepository ?? (Global.IoC.TryResolve<IRepository<TherapistCalendarEntry>>());
try
{
Encoding encoding = Encoding.UTF8;
string SyncTokenStr = "";
string PageTokenStr = "";
if (pagingToken != null)
PageTokenStr = "&pageToken=" + pagingToken;
if (therapist.SyncTokenGoogleCalendar != null)
SyncTokenStr = "&syncToken=" + therapist.SyncTokenGoogleCalendar;
var request = (HttpWebRequest)WebRequest.Create(new Uri(@"https://www.googleapis.com/calendar/v3/calendars/primary/events?showDeleted=true" + PageTokenStr + SyncTokenStr, UriKind.Absolute));
if (therapist.RefreshTokenGoogle != null)
{
var authenticator = GetAuthenticator(therapist);
GoogleAuthorizationHelper.apply((GoogleApiUtils.GoogleAuthenticator)authenticator, request);
}
request.Method = "GET";
request.ContentType = "application/json";
try
{
var response = (HttpWebResponse)request.GetResponse();
string jsonString = GetResponseJson(response);
PrintResponseJson(jsonString, "sync from google calendar");
var data = (JObject)JsonConvert.DeserializeObject(jsonString);
if (data["nextPageToken"] != null)
{
if (syncAllEvents == true)
{
AddGoogleCalendarEventToTipulog(therapist, TherapistCalendarEntryRepositoryCallback, data);
}
SyncGoogleCalendarEvents(therapist, data["nextPageToken"].ToString(), syncAllEvents);
}
else
{
saveTherapistNextToken(therapist, TherpistRepisitoryCallback, data);
if (syncAllEvents == true)
{
AddGoogleCalendarEventToTipulog(therapist, TherapistCalendarEntryRepositoryCallback, data);
}
}
}
catch (WebException e)
{
...
}
catch (Exception e)
{
...
}
}
catch (Exception e)
{
...
}
}
我有一个教程展示了如何设置 MVC 项目以供 Google 人 api Asp .net core 3 and Google login
授权
一旦你设置了 DI,你就可以调用你想要的 API。
// This configures Google.Apis.Auth.AspNetCore3 for use in this app.
services
.AddAuthentication(o =>
{
// This forces challenge results to be handled by Google OpenID Handler, so there's no
// need to add an AccountController that emits challenges for Login.
o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// This forces forbid results to be handled by Google OpenID Handler, which checks if
// extra scopes are required and does automatic incremental auth.
o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// Default scheme that will handle everything else.
// Once a user is authenticated, the OAuth2 token info is stored in cookies.
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogleOpenIdConnect(options =>
{
options.ClientId = ClientId;
options.ClientSecret = ClientSecret;
});
博客有一个配套视频 post How to get a Google users profile information, with C#. 但它与 Google 人 api。
这里是一个如何针对 google 日历 api 调整它的示例。
/// <summary>
/// List all calendars in a users Calendar List.
/// </summary>
/// <param name="auth"></param>
/// <returns></returns>
[GoogleScopedAuthorize(CalendarService.ScopeConstants.Calendar)]
public async Task<IActionResult> Index([FromServices] IGoogleAuthProvider auth)
{
var cred = await auth.GetCredentialAsync();
var service = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = cred
});
var response = await service.CalendarList.List().ExecuteAsync();
return View(response);
}
我正在为 Google 日历编辑视频
我正在尝试从 google 日历同步到我的 .NET MVC Web 应用程序。
我创建了一个回调方法,Googles Calendar API
会将日历中的新事件发送到该回调方法。但是我没有得到新的 google 日历事件,而是得到了这个 error
:
2021-07-09 12:52:26,982 [ 37] DEBUG DotNetOpenAuth.Messaging - The following required parameters were missing from the DotNetOpenAuth.OAuth2.Messages.AccessTokenFailedResponse message: {error, }
2021-07-09 12:52:26,997 [ 37] WARN DotNetOpenAuth.Messaging
Multiple message types seemed to fit the incoming data: {AccessTokenSuccessResponse (2.0), UnauthorizedResponse (2.0), }2021-07-09 12:52:27,013 [ 37] DEBUG DotNetOpenAuth.Messaging.Channel
Received AccessTokenSuccessResponse response.2021-07-09 12:52:27,013 [ 37] INFO DotNetOpenAuth.Messaging.Channel
Processing incoming AccessTokenSuccessResponse (2.0) message: access_token: <Access_Token_Number> token_type: Bearer expires_in: 3599 scope: https://www.googleapis.com/auth/calendar2021-07-09 12:52:27,013 [ 37] DEBUG DotNetOpenAuth.Messaging.Channel
After binding element processing, the received AccessTokenSuccessResponse (2.0) message is: access_token: <Access_Token_Number> token_type: Bearer expires_in: 3599 scope: https://www.googleapis.com/auth/calendar
我该如何处理?
编辑(添加代码)
public void PushNotificationCallback()
{
try
{
var header = Request.Headers;
NotificationResponse notification = new NotificationResponse(header["X-Goog-Channel-Expiration"], header["X-Goog-Channel-Id"], header["X-Goog-Message-Number"], header["X-Goog-Resource-Id"], header["X-Goog-Resource-State"], header["X-Goog-Channel-Token"], header["X-Goog-Resource-Uri"]);
therapistCalendarEntryController.PushNotificationCallback (notification);
}
catch (Exception e)
{
...
}
}
并在控制器动作中
public void PushNotificationCallback(NotificationResponse response)
{
if (!string.IsNullOrEmpty(response?.HTTP_X_GOOG_CHANNEL_TOKEN)) surrounded with if
{
var TherpistRepisitoryCallback = TherapistRepository ?? (Global.IoC.TryResolve<IRepository<Therapist>>());
var therapistId = new Guid(response.HTTP_X_GOOG_CHANNEL_TOKEN);
var therapistCall = TherpistRepisitoryCallback.Get(therapistId);
if (therapistCall != null)
{
SyncGoogleCalendarEvents(therapistCall, null, true);
}
}
}
public void SyncGoogleCalendarEvents(Therapist therapist, string pagingToken, bool syncAllEvents)
{
var TherpistRepisitoryCallback = TherapistRepository ?? (Global.IoC.TryResolve<IRepository<Therapist>>());
var TherapistCalendarEntryRepositoryCallback = TherapistCalendarEntryRepository ?? (Global.IoC.TryResolve<IRepository<TherapistCalendarEntry>>());
try
{
Encoding encoding = Encoding.UTF8;
string SyncTokenStr = "";
string PageTokenStr = "";
if (pagingToken != null)
PageTokenStr = "&pageToken=" + pagingToken;
if (therapist.SyncTokenGoogleCalendar != null)
SyncTokenStr = "&syncToken=" + therapist.SyncTokenGoogleCalendar;
var request = (HttpWebRequest)WebRequest.Create(new Uri(@"https://www.googleapis.com/calendar/v3/calendars/primary/events?showDeleted=true" + PageTokenStr + SyncTokenStr, UriKind.Absolute));
if (therapist.RefreshTokenGoogle != null)
{
var authenticator = GetAuthenticator(therapist);
GoogleAuthorizationHelper.apply((GoogleApiUtils.GoogleAuthenticator)authenticator, request);
}
request.Method = "GET";
request.ContentType = "application/json";
try
{
var response = (HttpWebResponse)request.GetResponse();
string jsonString = GetResponseJson(response);
PrintResponseJson(jsonString, "sync from google calendar");
var data = (JObject)JsonConvert.DeserializeObject(jsonString);
if (data["nextPageToken"] != null)
{
if (syncAllEvents == true)
{
AddGoogleCalendarEventToTipulog(therapist, TherapistCalendarEntryRepositoryCallback, data);
}
SyncGoogleCalendarEvents(therapist, data["nextPageToken"].ToString(), syncAllEvents);
}
else
{
saveTherapistNextToken(therapist, TherpistRepisitoryCallback, data);
if (syncAllEvents == true)
{
AddGoogleCalendarEventToTipulog(therapist, TherapistCalendarEntryRepositoryCallback, data);
}
}
}
catch (WebException e)
{
...
}
catch (Exception e)
{
...
}
}
catch (Exception e)
{
...
}
}
我有一个教程展示了如何设置 MVC 项目以供 Google 人 api Asp .net core 3 and Google login
授权一旦你设置了 DI,你就可以调用你想要的 API。
// This configures Google.Apis.Auth.AspNetCore3 for use in this app.
services
.AddAuthentication(o =>
{
// This forces challenge results to be handled by Google OpenID Handler, so there's no
// need to add an AccountController that emits challenges for Login.
o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// This forces forbid results to be handled by Google OpenID Handler, which checks if
// extra scopes are required and does automatic incremental auth.
o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// Default scheme that will handle everything else.
// Once a user is authenticated, the OAuth2 token info is stored in cookies.
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogleOpenIdConnect(options =>
{
options.ClientId = ClientId;
options.ClientSecret = ClientSecret;
});
博客有一个配套视频 post How to get a Google users profile information, with C#. 但它与 Google 人 api。
这里是一个如何针对 google 日历 api 调整它的示例。
/// <summary>
/// List all calendars in a users Calendar List.
/// </summary>
/// <param name="auth"></param>
/// <returns></returns>
[GoogleScopedAuthorize(CalendarService.ScopeConstants.Calendar)]
public async Task<IActionResult> Index([FromServices] IGoogleAuthProvider auth)
{
var cred = await auth.GetCredentialAsync();
var service = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = cred
});
var response = await service.CalendarList.List().ExecuteAsync();
return View(response);
}
我正在为 Google 日历编辑视频