3

我正在构建一个 Windows 8 应用程序,并在应用程序启动时尝试从 Google 数据 API 获取令牌。我构建了一个函数来执行此操作,它具有以下代码:

string authCodeUrl = UrlHelpers.BaseUrlFactory(UrlType.OAuth) +
                    "?client_id=" + _clientId +
                    "&redirect_uri=" + _redirectUri +
                    "&response_type=code" +
                    "&scope=" + _scope;

Uri startUri = new Uri(authCodeUrl);
Uri endUri = new Uri("https://accounts.google.com/o/oauth2/approval?");

WebAuthenticationResult webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, startUri, endUri);

OnLaunched()在调用之前,我在 App.xaml.cs 中调用该函数Window.Current.Activate()。我这样做的原因是因为我的MainViewModel.

奇怪的是:当我以正常方式(通过 Visual Studio)启动我的应用程序时,它会卡在启动画面上(启动画面会持续很长时间),但是当我在这一行上放置一个断点时:

WebAuthenticationResult webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, startUri, endUri);

一步一步通过它,我突然得到一个登录窗口,允许我登录并获取令牌,这意味着启动画面消失了,我可以使用我的应用程序。

当我从 App.xaml.cs 中删除调用并仅从 ViewModel 请求令牌时,我遇到了同样的问题:它仍然卡在 SplashScreen 上。当我确实从我的 App.xaml.cs 请求令牌但在Window.Current.Activate()调用后移动请求时,我也遇到了这个问题。但在这些情况下,登录后启动画面消失,但屏幕保持黑色。我没有看到我的应用程序。

Ps,这就是我从 App.xaml.cs 请求令牌的方式(OnLaunched标记为async):

IOAuth2Service oAuth2Service = new OAuth2Service();
await oAuth2Service.GetToken();

OAuth2Service 只是一个有方法的对象GetToken()。这种方法只是做我上面描述的。

有谁知道为什么当我使用断点单步执行应用程序时它会起作用,但当我不单步执行它就启动它时却不行?

我已经隔离了问题并创建了一个仅包含此代码的 Github 项目。你可以在这里找到它:https ://github.com/Avalaxy/OAuth2WinRT/tree/master/App1 。有一个 app.xaml.cs 调用 OAuth2.GetToken()。

4

1 回答 1

3

根据文档-

如果应用程序或其启动画面保持在屏幕上,则没有时间限制,但最终应用程序需要调用激活才能进行。

诚然有点含糊,需要解释,但在GetToken请求之前将调用移动到激活将使您摆脱看似潜在的竞争条件。

于 2013-03-30T06:54:48.843 回答