Xamarin表示http异步请求

时间:2017-05-17 15:16:21

标签: c# asynchronous xamarin.forms httpclient prism

我正在尝试对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或棱镜设置?

1 个答案:

答案 0 :(得分: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();
}