Вызов метода PostAsync приводит к сбою приложения - PullRequest
0 голосов
/ 15 мая 2019

Я пытаюсь отправить информацию о пользователе на сервер, используя метод 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 голосов
/ 15 мая 2019

Я немного изменил свой код

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);
                }

При изменении void на Task я получаю эту ошибку: Position 12:54. Signature (return type) of EventHandler "SmartLockApp.Views.LoginPage.SignInProcedure" doesn't match the event type

А также, если я не изменил void на Task, я не смогу найти ошибку в консоли

0 голосов
/ 15 мая 2019

В SignInProcedure вместо async void используйте async Task, а также добавьте блок try catch и check.

...