异步http请求不起作用(未知错误)

时间:2018-03-20 10:05:29

标签: c# http asynchronous httpclient

我只想通过https发送登录数据并接收回复。整个过程在Visual Studio 2017中运行。当我单击"登录按钮"时运行程序停止。我也没有真正的错误,但只有一个未处理的例外。

我是C#的新手,也许我对异步做错了什么?在此先感谢:)

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

2 个答案:

答案 0 :(得分:2)

我看到的唯一问题是你没有标记你的事件处理程序async。您需要将其标记为async,并等待您调用的方法返回的Task

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

并且一个好的做法是使用async对方法名称进行后缀,如果它可以异步运行:

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

您需要了解有关asyncawait的更多信息才能正确使用它们。您可以阅读https://aka.ms/logicexpressions了解更多详情并更好地了解它。

答案 1 :(得分:2)

GetResponseText未返回string,它会返回Task(实际上应该命名为GetResponseTextAsync)。您需要await该任务,或Wait Result

无论

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

或更好:

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