c# - Xamarin Forms 错误处理 - 消息中心警报未从数据存储中显示

标签 c# xamarin.ios xamarin.forms xamarin.android

我在读this在消息中心发帖。当我在我的数据存储类中遇到错误时,我想使用这种方法来显示错误(如果这不是 kosher,请告诉我)。但是,它不起作用。

登录页面.xaml.cs

public partial class LoginPage : ContentPage
{
    public LoginPage()
    {
        InitializeComponent();

        MessagingCenter.Subscribe<LoginDataStore, MessagingCenterAlert>(this, "message", (sender, arg) =>
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                DisplayAlert("UH OH!", arg.Message, "OK");
            });
        });
    }
}

登录数据存储.cs

public class LoginDataStore
{
    HttpClient client;

    public LoginDataStore()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri($"{App.BackendUrl}/");
    }

    public async void Login(string username, string password)
    {
        var content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("email", username),
            new KeyValuePair<string, string>("password", password)
        });

        try
        {
            var result = await client.PostAsync("/oauth/token", content);

            string resultContent = await result.Content.ReadAsStringAsync();

            if (!result.IsSuccessStatusCode)
                throw new Exception(result.StatusCode.ToString() + System.Environment.NewLine + "Please check your email and password.");

            dynamic resultObject = JsonConvert.DeserializeObject(resultContent);

            Settings.AuthToken = (string)resultObject["access_token"].Value;

            Settings.UserId = username;
        }
        catch (Exception e)
        {
            // remove later when the messaging center works 
            await Application.Current.MainPage.DisplayAlert("Login Failed!", e.Message, "OK");

            MessagingCenter.Send(new MessagingCenterAlert
            {
                Title = "Login Failed",
                Message = e.Message,
                Cancel = "OK"
            }, e.Message);

            return;
        }
    }
}

当我运行带有断点的代码时,我可以看到正在创建消息并且订阅了登录页面,但是订阅中的代码永远不会被调用并且没有消息出现。直接调用页面的蛮力代码可以工作,但并不十分优雅。

最佳答案

你的订阅者没有监听发送者发送的相同的message键。他们需要像这样匹配:

MessagingCenter.Subscribe<LoginDataStore, MessagingCenterAlert> (this, "LoginFailureMessage", (sender, args) => {
    // do something whenever the "LoginFailureMessage" message is sent
});

MessagingCenter.Send<LoginDataStore, MessagingCenterAlert> (this, "LoginFailureMessage", new MessagingCenterAlert
        {
            Title = "Login Failed",
            Message = e.Message,
            Cancel = "OK"
        });

关于c# - Xamarin Forms 错误处理 - 消息中心警报未从数据存储中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47687012/

相关文章:

c# - 使用 BinaryReader 读取 "string in little-endian UTF-16 encoding"

listview - Xamarin.Forms ListView 禁用 UWP 上的选择

C# Xamarin 安卓 "Central Directory record could not be found"

c# - 联网流程

c# - 用 NSubstitute 模拟表达式

c# - WPF、MVVM、NUnit 和线程……我做错了吗

ios - 我们可以从 swift 框架生成 Objective-C 静态库吗?

xamarin - 如何使用Akavache实现大数据的搜索?

.net - 在 monotouch 中使用 .net dll 时找不到 DLL

c# - Xamarin.Forms.Navigation.PopAsync() 不弹出页面