Calling the PostAsync method crashes the application

nekknekk Member

I'm trying to send user information to a server using the post method. When I call an async Task, it immediatly crashes.

Here's what I have in 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
            {
                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)
                {

                    Debug.WriteLine(ex);
                }

            }

And here in the 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;
        }

The server should receive the user data, but it's not receiving anything.
The app crashes before putting the exception in the debug console.

Tagged:

Answers

  • SmielSmiel USMember ✭✭

    I used your code as is, without any error, but no data was sent to the API. I then changed FormUrlEncodedContent to StringContent and the list was sent to the API.

    Below is my API method (MVC API Controller) as well as your code with my changes.

    [Route("SecureAPI/LoginTest")]
    [HttpPost]
    public Token LoginTest(List<KeyValuePair<string, string>> postData)
    {
         // Some logic to return Token
    }
    
    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 json = JsonConvert.SerializeObject(postData);
        var content = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
    
        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;
    
    }
    
    // Replaced FormUrlEncodedContent with StringContent
    public async Task<T> PostResponseLogin<T>(string weburl, StringContent 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;
    }
    
  • nekknekk Member

    I tried your code and it still crashes :/

  • FaizalSaidaliFaizalSaidali USMember ✭✭

    @nekk , Just an observation, You put the DisplayAlert code inside of Main thread(Device.BeginInvokeMainThread).

  • SmielSmiel USMember ✭✭

    Try below, and add breakpoints inside the if and else sections to see if the code gets executed.
    Also, have you debugged the code on the API side to see if the data you're sending and the code that generates the token behaves as expected ?

    public async Task<T> PostResponseLogin<T>(string weburl, StringContent content, HttpClient client) where T : class
    {
        var response = await client.PostAsync(weburl, content);
        if (response.IsSuccessStatusCode)
        {
            var jsonResult = response.Content.ReadAsStringAsync().Result;
    
            var responseObject = JsonConvert.DeserializeObject<T>(jsonResult);
    
            return responseObject;
        }
        else
        {
            throw new Exception($"{response.StatusCode}");
        } 
    }
    
Sign In or Register to comment.