簡體   English   中英

Xamarin Forms http異步請求

[英]Xamarin Forms http async request

我正在嘗試對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;
        }



    }
}

如果我嘗試在命令中執行帶有wait的相同操作,那么我不會處理相同的錯誤,但是如果我等待,它將正常工作,但是在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或棱鏡有什么設置嗎?

我也有同樣奇怪的錯誤...我使用此替代方法修復(使用包裝異步任務的異步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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM