调用PostAsync方法会使应用程序崩溃

时间:2019-05-15 13:24:01

标签: c# xamarin xamarin.forms dotnet-httpclient

我正在尝试使用post方法将用户信息发送到服务器。当我调用异步任务时,它立即崩溃。

这是我在LoginPage.cs中拥有的

 async void SignInProcedure(object sender, EventArgs e) //function called when pressing the signin button
        {

            User user = new User(Entry_Username.Text, Entry_Password.Text); //putting username and password entered by the user in the entry box
            if (user.CheckInformation())//checks if the boxes are empty
            {

                var result = await App.RestService.Login(user);//RestService class
                await App.Current.MainPage.DisplayAlert("Login", "Login Successful", "Oke");

在RestService.cs中

public async Task<Token> Login(User user)//this is where the problem is
        {

            var postData = new List<KeyValuePair<string, string>>();            
            postData.Add(new KeyValuePair<string, string>("grant_type", grant_type));
            postData.Add(new KeyValuePair<string, string>("username", user.Username));
            postData.Add(new KeyValuePair<string, string>("password", user.Password));
            var content = new FormUrlEncodedContent(postData);
            var response = await PostResponseLogin<Token>(Constants.LoginUrl, content);
            DateTime dt = new DateTime();
            dt = DateTime.Today;
            response.expire_date = dt.AddSeconds(response.expire_in);
            return response;

        }

        public async Task<T> PostResponseLogin<T>(string weburl, FormUrlEncodedContent content) where T : class
        {

            var response = await client.PostAsync(weburl,content);

            var jsonResult = response.Content.ReadAsStringAsync().Result;

            var responseObject = JsonConvert.DeserializeObject<T>(jsonResult);

            return responseObject;
        }

服务器应接收用户数据,但未接收任何数据。 我似乎找不到任何错误消息。

2 个答案:

答案 0 :(得分:0)

使用SignInProcedure而不是使用异步void,请使用异步Task并添加try catch块并进行检查。

答案 1 :(得分:0)

我修改了我的代码

react-native run-android

将void更改为Task时,出现以下错误:async Task SignInProcedure(object sender, EventArgs e) //function called when pressing the signin button { User user = new User(Entry_Username.Text, Entry_Password.Text); //putting username and password entered by the user in the entry box if (user.CheckInformation())//checks if the boxes are empty { try { var result = await App.RestService.Login(user);//RestService class await App.Current.MainPage.DisplayAlert("Login", "Login Successful", "Oke"); if (result.access_token != null) { App.UserDatabase.SaveUser(user); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); }

而且,如果我没有将Task的void更改为零,那么我将无法在控制台中找到错误