【问题标题】:Xamarin Forms http async requestXamarin 表单 http 异步请求
【发布时间】:2017-05-17 15:16:21
【问题描述】:

我正在尝试对 Web 服务进行异步调用。 我想在打开应用程序 (App.xaml.cs) 时进行此调用。 根据返回给我的答案,它必须导航到特定页面 但我不工作。

public partial class App : PrismApplication
{
    public App(IPlatformInitializer initializer = null) : base(initializer) { }

    protected override void OnInitialized()
    {
        InitializeComponent();
        try
        {
            CheckLogin().Wait();


        }
        catch (Exception e)
        {
            var t = e;
        }
    }
    private static async Task CheckLogin()
    {


        try
        {
            var login = new Login
            {
                Email = "test@test.com",
                Password = "test",
            };
            var client = new HttpClient { BaseAddress = new Uri("http://www.api.com/test/") };
            var data = JsonConvert.SerializeObject(login);

            var content = new StringContent(data, Encoding.UTF8, "application/json");
            var response = await client.PostAsync(@"api/it-IT/auth/token", content);  //crash without error, freeze
            if (response.IsSuccessStatusCode)
            {
                var successResult = JsonConvert.DeserializeObject<HttpResponseMessage>(response.Content.ReadAsStringAsync().Result);
                if (successResult != null)
                {
                    //return true;
                }
                else
                {
                    //return false;
                }
            }


        }
        catch (Exception e)
        {
            var t = e;
        }



    }
    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation<NavigationPage>();
        Container.RegisterTypeForNavigation<MainPage>();
        Container.RegisterTypeForNavigation<MainPage2>();
        Container.RegisterTypeForNavigation<MainPage3>();
    }


}

什么时候 postasync 调用不继续向前,不是我没有收到错误,但不继续。

但如果我在应用程序控制台中尝试相同的代码,一切正常,为什么?

  class Program
{

        static void Main(string[] args)
        {
            Console.WriteLine("A");

            CheckLogin().Wait();

            Console.WriteLine("K");
            Console.ReadKey();
        }


    private static async Task CheckLogin()
    {


        try
        {
            var login = new Login
            {
                Email = "test@test.com",
                Password = "@test",
            };
            var client = new HttpClient { BaseAddress = new Uri("http://www.api.com/test/") };
            var data = JsonConvert.SerializeObject(login);

            var content = new StringContent(data, Encoding.UTF8, "application/json");
            var response = await client.PostAsync(@"api/it-IT/auth/token", content);
            if (response.IsSuccessStatusCode)
            {

            }


        }
        catch (Exception e)
        {
            var t = e;
        }



    }
}

如果我尝试在带有等待的命令中执行相同的操作,则不会出现相同的错误,但如果我等待,它将正常工作,但在 OnInitialized() 中的 App.xaml.cs 中我无法放置等待

     public DelegateCommand callCommand { get; set; }
        public MainPage2ViewModel()
        {
            callCommand = new DelegateCommand(Call);
        }

        private  void Call()
        {
            //await CheckLogin(); // work 
            CheckLogin().Wait(); // not work the same problem
            var i = "pippo";
        }
        private async Task CheckLogin()
        {
         ....
        }

有什么可以用 xamarin 或 prism 设置的吗?

【问题讨论】:

    标签: c# asynchronous xamarin.forms httpclient prism


    【解决方案1】:

    我也遇到了同样奇怪的错误... 我修复了这个解决方法(使用包装异步任务的异步 void)...

    public App()
    {
        InitializeComponent();
        Current.MainPage = new LoadingPage();
    }
    
    protected override void OnStart()
    {
        MagicInit();
        base.OnStart();
    }
    
    public static async void MagicInit()
    {
        var f = await FileSystem.Current.LocalStorage.CreateFileAsync("db.sqlite", CreationCollisionOption.OpenIfExists);
        DbConnection = f.Path;
        await DataService.DbFill();
        User = await DataService.Instance.Table<SpUser>().FirstOrDefaultAsync();
        Current.MainPage = User != null ? (Page)new MainPage() : new LoginPage();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 2012-04-03
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      • 2018-04-10
      • 2017-07-09
      相关资源
      最近更新 更多