适用于UWP Windows 10应用程序的Google Calendar API发生一个或多个错误 [英] Google Calendar API for UWP Windows 10 Application One or more errors occurred

查看:91
本文介绍了适用于UWP Windows 10应用程序的Google Calendar API发生一个或多个错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Google Calendar API v3,但是在运行代码时遇到问题,它总是给我该错误:

I'm trying to use Google Calendar API v3, but i have problems while running the codes, it always gives me that error :

mscorlib.ni.dll中发生类型'System.AggregateException'的异常,但未在用户代码中处理 附加信息:发生一个或多个错误.

An exception of type 'System.AggregateException' occurred in mscorlib.ni.dll but was not handled in user code Additional information: One or more errors occurred.

我不知道为什么这么做,它也应该工作.这是它的屏幕截图:

I don't know why it does, also It should work as well. Here is a screenshot for it :

我的代码也是:

 UserCredential credential;
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                   new Uri("ms-appx:///Assets/client_secrets.json"),
                    Scopes,
                    "user",
                    CancellationToken.None).Result;


            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

        var calendarService = new CalendarService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
            ApplicationName = "Windows 10 Calendar sample"
        });
        var calendarListResource = await calendarService.CalendarList.List().ExecuteAsync();

如果至少可以帮助您通过REST API调用它,那也很好,但是您必须考虑到它是UWP,因此它还有另一种使它正常工作的方法. 正如我已经尝试通过REST API进行的操作一样,但是我始终会收到请求错误代码400".

If you can at least help with calling it through REST API, that would be great too, but you must consider that it's UWP, so it has another way to get it work as well. As i already tried through REST API, but i always get "Request error code 400".

感谢您的关注.

推荐答案

.NET的Google API客户端库目前不支持UWP.因此,我们不能使用 Google.Apis.Calendar.v3客户端库现在在UWP应用中.有关更多信息,请参见类似的问题:带有Google日历的通用Windows平台应用程序.

The Google API Client Library for .NET does not support UWP by now. So we can't use Google.Apis.Calendar.v3 Client Library in UWP apps now. For more info, please see the similar question: Universal Windows Platform App with google calendar.

要在UWP中使用Google Calendar API,我们可以通过REST API对其进行调用.要使用REST API,我们需要先授权请求.有关如何授权请求的信息,请参见授权对Google Calendar API的请求针对移动和桌面应用程序使用OAuth 2.0.

To use Google Calendar API in UWP, we can call it through REST API. To use the REST API, we need to authorize requests first. For how to authorize requests, please see Authorizing Requests to the Google Calendar API and Using OAuth 2.0 for Mobile and Desktop Applications.

获得访问令牌后,我们可以调用Calendar API,如下所示:

After we have the access token, we can call Calendar API like following:

var clientId = "{Your Client Id}";
var redirectURI = "pw.oauth2:/oauth2redirect";
var scope = "https://www.googleapis.com/auth/calendar.readonly";
var SpotifyUrl = $"https://accounts.google.com/o/oauth2/auth?client_id={clientId}&redirect_uri={Uri.EscapeDataString(redirectURI)}&response_type=code&scope={Uri.EscapeDataString(scope)}";
var StartUri = new Uri(SpotifyUrl);
var EndUri = new Uri(redirectURI);

// Get Authorization code
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
    var decoder = new WwwFormUrlDecoder(new Uri(WebAuthenticationResult.ResponseData).Query);
    if (decoder[0].Name != "code")
    {
        System.Diagnostics.Debug.WriteLine($"OAuth authorization error: {decoder.GetFirstValueByName("error")}.");
        return;
    }

    var autorizationCode = decoder.GetFirstValueByName("code");


    //Get Access Token
    var pairs = new Dictionary<string, string>();
    pairs.Add("code", autorizationCode);
    pairs.Add("client_id", clientId);
    pairs.Add("redirect_uri", redirectURI);
    pairs.Add("grant_type", "authorization_code");

    var formContent = new Windows.Web.Http.HttpFormUrlEncodedContent(pairs);

    var client = new Windows.Web.Http.HttpClient();
    var httpResponseMessage = await client.PostAsync(new Uri("https://www.googleapis.com/oauth2/v4/token"), formContent);
    if (!httpResponseMessage.IsSuccessStatusCode)
    {
        System.Diagnostics.Debug.WriteLine($"OAuth authorization error: {httpResponseMessage.StatusCode}.");
        return;
    }

    string jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
    var jsonObject = Windows.Data.Json.JsonObject.Parse(jsonString);
    var accessToken = jsonObject["access_token"].GetString();


    //Call Google Calendar API
    using (var httpRequest = new Windows.Web.Http.HttpRequestMessage())
    {
        string calendarAPI = "https://www.googleapis.com/calendar/v3/users/me/calendarList";

        httpRequest.Method = Windows.Web.Http.HttpMethod.Get;
        httpRequest.RequestUri = new Uri(calendarAPI);
        httpRequest.Headers.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", accessToken);

        var response = await client.SendRequestAsync(httpRequest);

        if (response.IsSuccessStatusCode)
        {
            var listString = await response.Content.ReadAsStringAsync();
            //TODO
        }
    }
}

这篇关于适用于UWP Windows 10应用程序的Google Calendar API发生一个或多个错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆