繁体   English   中英

登录而不重定向(或为什么LoginAsync()抛出System.UnauthorizedAccessException的原因)

[英]Login without redirecting (or why LoginAsync() throws System.UnauthorizedAccessException)

我正在使用Windows Phone 8的Facebook.Client,以便处理游戏中通过Facebook进行的用户登录。

我正在使用Facebook.Client.FacebookSessionClient.LoginWithApp()实现Facebook登录功能,但是,这始终会导致重定向到我的应用程序页面之一。 我使用MonoGame / XNA制作游戏,所以我的应用程序仅包含游戏页面,游戏的每个部分都被绘制到其中。 重定向到它时,我失去了游戏的“进度”(因为重定向,游戏在主菜单中再次重新启动)。

这种行为使我尝试使用Facebook.Client.FacebookSessionClient.LoginAsync() (我仍然不知道它的作用,因为我在某处找不到它,但是如果不引起重定向,那就是我所需要的) 。

我目前正在尝试使用LoginAsync()处理登录,但是会LoginAsync()此异常:

System.UnauthorizedAccessException:无效的跨线程访问。

这是我正在使用的代码(请注意,try-catch语句用于捕获确切的异常,否则,我只会得到System.AggregateException ):

FacebookSessionClient fb = new FacebookSessionClient(AppId);

Task<FacebookSession> fbst = null;
FacebookSession fbs = null;

try
{
    fbst = fb.LoginAsync("basic_info");
    fbs = fbst.Result;
}
catch (AggregateException e)
{
    Debug.WriteLine(e.ToString());
    Debug.WriteLine(e.Message);
}

是什么导致未授权访问异常? 另外,如果可以使用LoginWithApp()而不进行重定向(或其他任何形式的无需重定向的登录),也可以做到这一点。

我设法找到此问题的解决方案。 之所以发生这种情况,是因为显然在使用MonoGame时无法访问Application.Current.RootVisual ,从而引发此异常。

Windows 8和Windows Phone 8游戏开发一书的第438页所述:

Windows Phone应用程序无法从游戏类代码中与XAML控件进行交互,因为游戏代码在不允许访问UI组件的不同线程中运行。 为了解决这个问题,Dispatcher对象用于将更新排队,以供UI线程处理。

在Facebook.Client的代码(在其GitHub repo中可用)中, PhoneWebAuthentication.cs中有一行可以执行以下操作:

PhoneApplicationFrame rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;

这是导致异常并破坏LoginAsync()行为的LoginAsync()

我已经在他们的GitHub页面上打开了一个问题

现在,如果您希望LoginAsync()使用MonoGame在WP8中工作(它不会导致重定向,因此正是我想要的!),则需要从以下位置下载Facebook.Windows Phone 8的源代码上面提到的GitHub存储库,并将其链接到您的项目中。 之后,使AuthenticateAsync()函数如下所示:

public static Task<WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri startUri, Uri endUri)
{
    if (options != WebAuthenticationOptions.None)
    {
        throw new NotImplementedException("This method does not support authentication options other than 'None'.");
    }

    WebAuthenticationBroker.StartUri = startUri;
    WebAuthenticationBroker.EndUri = endUri;
    WebAuthenticationBroker.AuthenticationInProgress = true;

    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        (Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/Facebook.Client;component/loginpage.xaml", UriKind.Relative));
    });

    Task<WebAuthenticationResult> task = Task<WebAuthenticationResult>.Factory.StartNew(() =>
    {
        authenticateFinishedEvent.WaitOne();
        return new WebAuthenticationResult(responseData, responseStatus, responseErrorDetail);
    });

    return task;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM