0

I simply want to send login data via https and receive the response. The whole thing runs in Visual Studio 2017. When running the program stops when I click the "Login button". I also get no real error but only an unhandled exception.

I'm new to C # maybe i did something wrong with async? Thanks in advance :)

 public static async Task<string> GetResponseText(string address)
 {
     using (var httpClient = new HttpClient())          
        return await httpClient.GetStringAsync(address);
 }

 public void On_Login_Listener(Object sender, EventArgs args)
 {
    string url = "https://localhost/login.php?email=" + email.Text+"&password="+password.Text;

    InfoBox.Text = GetResponseText(url).ToString();
 }
Bassie
  • 9,529
  • 8
  • 68
  • 159

2 Answers2

2

The only problem i see is you have not marked your event handler async. You need to to mark it async and await the Task that the method you calling is returning:

public async void On_Login_Listener(Object sender, EventArgs args)
{
    string url = "https://localhost/login.php?email=" + email.Text+"&password="+password.Text;

    InfoBox.Text = await GetResponseText(url);
}

and a good practice is to postfix the method name with async if it can run asynchrounously :

 public static async Task<string> GetResponseTextAsync(string address)
 {
     using (var httpClient = new HttpClient())          
        return await httpClient.GetStringAsync(address);
 }

You need to study more about async and await to be able to correctly use them. You can read this great post for more details and getting better understanding of it.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
2

GetResponseText does not return a string, it returns a Task (it should actually be named GetResponseTextAsync). You either need to await that task or Wait for its Result:

Either

public void On_Login_Listener(Object sender, EventArgs args)
{
    string url = "https://localhost/login.php?email=" + email.Text+"&password="+password.Text;

    InfoBox.Text = GetResponseText(url).Result;
}    

or better:

// declare as async
public async void On_Login_Listener(Object sender, EventArgs args)
{
    string url = "https://localhost/login.php?email=" + email.Text+"&password="+password.Text;

    InfoBox.Text = await GetResponseText(url);
}    
René Vogt
  • 43,056
  • 14
  • 77
  • 99