Google Calendar API V3

时间:2012-03-30 07:10:16

标签: c# .net oauth-2.0 google-calendar-api

我正在尝试使用Google Calendar API V3来更新我的日历。我想从C#代码中获取我的日历事件。我正在使用.Net Library for Google Calendar API V3。

由于某种原因,我无法授权我的请求。我试图按照可用的代码示例,但是徒劳无功。以下是我用于授权我的请求的代码片段:

    private void GetEvents()
    {
        var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description,MyClientId, MySecurityId);
        var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

        CalendarService myService = new CalendarService(auth);  
        try
        {
            Events result = myService.Events.List(MyCalendarId).Fetch();

            if (result.Items.Count > 0)
            {
            }
        }
        catch (Google.GoogleApiRequestException ex)
        {
            //throw ex;
        }
    }

    private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
    {
        IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/calendar.readonly" });

        state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);          

        if (!string.IsNullOrEmpty(refreshToken)) // refreshToken you stored in step 4
        {
            try
            {
                state.RefreshToken = refreshToken;
                if (arg.RefreshToken(state))     // This is calling out to the OAuth servers with the refresh token getting back a session token, returns true if successful.
                {
                    if (state.RefreshToken != refreshToken) // if the refresh token has changed, save it.
                    {
                        //PersistRefreshToken(authorization.RefreshToken);
                    }
                    return state; // Retain the authorization state, this is what will authenticate your calls.
                }
            }
            catch (ProtocolException ex) { throw ex; }
        }
        return state;
    } 

执行if (arg.RefreshToken(state))时收到此异常:

  

协议异常发送直接消息或

时发生错误      

得到答复。

请帮助!!!

1 个答案:

答案 0 :(得分:0)

您是在Web服务器上还是在本机应用程序中使用它?您拥有的此代码仅适用于本机应用程序,因此可能是您的麻烦。