我正在使用MVVM Light开发Windows 8.1应用程序(XAML / C#)。
我曾经将LiveId保存在代码中仅用于调试,但现在是时候进行LogIn了。
目前我仍然坚持使用这段代码:
this.authClient = new LiveAuthClient();
LiveLoginResult loginResult = await this.authClient.InitializeAsync(scopes);
它一直给我错误:
类型' System.NullReferenceException'的例外情况发生在mscorlib.dll中但未在用户代码中处理
附加信息:对象引用未设置为的实例 对象
源代码:
private static readonly string[] scopes =
new string[] {
"wl.signin",
"wl.basic",
"wl.offline_access"};
private LiveAuthClient authClient;
private LiveConnectClient liveClient;
public DashboardView()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
this.InitializePage();
}
private async void InitializePage()
{
this.authClient = new LiveAuthClient();
LiveLoginResult loginResult = await this.authClient.InitializeAsync(scopes);
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
if (this.authClient.CanLogout)
{
this.btnLogin.Content = "Sign Out";
}
else
{
this.btnLogin.Visibility = Visibility.Collapsed;
}
this.liveClient = new LiveConnectClient(loginResult.Session);
this.GetMe();
}
}
private async void btnLogin_Click(object sender, RoutedEventArgs e)
{
if (this.btnLogin.Content.ToString() == "Sign In")
{
LiveLoginResult loginResult = await this.authClient.LoginAsync(scopes);
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
if (this.authClient.CanLogout)
{
this.btnLogin.Content = "Sign Out";
}
else
{
this.btnLogin.Visibility = Visibility.Collapsed;
}
this.liveClient = new LiveConnectClient(loginResult.Session);
this.GetMe();
}
}
else
{
this.authClient.Logout();
this.btnLogin.Content = "Sign In";
}
}
private async void GetMe()
{
Task<LiveOperationResult> task = this.liveClient.GetAsync("me");
var result = await task;
dynamic profile = result.Result;
}
我甚至尝试了一些不同的范围,这是我的最后一次尝试。
提前致谢。
答案 0 :(得分:1)
据我所知,通过接口和/或类库调用LiveAuthClient.LoginAsync
时,我的问题就出现了。为了解决这个问题,我使用了MVVMLight库中的mediator Messenger
类来从与商店关联的应用程序入口项目中进行登录。要将应用与商店相关联,请按照本文http://www.codeproject.com/Articles/708863/Developer-Guide-to-Write-Windows-Store-App-usi进行操作。
我的视图模型位于单独的(可移植)库中,它们引用包含服务接口的契约库,以便在不NullReferenceException
创建消息类的情况下登录。
此解决方案适用于WP8.1,但由于平台共享相同的SDK,因此它应该可行。在示例代码中,我使用了来自MVVM light的Messenger和SimpleIoc。
消息类:
public class OneDriveLoginRequestMessage
{
public Action CallbackAction { get; set; }
}
注册OneDriveClient
的实例(或者你正在调用你的包装器)我正在使用MVVMLight SimpleIoc
SimpleIoc.Default.Register(() => new OneDriveClient());
方法App.xaml.cs
中的RootFrame_FirstNavigated
内部文件,请在登录时添加以下代码:
Messenger.Default.Register<OneDriveLoginRequestMessage>(this, async (msg) =>
{
await SimpleIoc.Default.GetInstance<OneDriveClient>().Login();
if (msg != null && msg.CallbackAction != null)
{
msg.CallbackAction();
}
});
最后从视图模型登录:
private void NavigateToOneDrivePage()
{
MessengerInstance.Send(new OneDriveLoginRequestMessage
{
CallbackAction = async () =>
{
// after login continue here...
var client = SimpleIoc.Default.GetInstance<OneDriveClient>();
}
});
}
我希望能解决你的问题。
最好,M