繁体   English   中英

异步http请求无法正常工作(未知错误)

[英]async http request is not working (unknown error)

我只想通过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();
 }

我看到的唯一问题是您尚未将事件处理程序标记为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);
}

一个好的做法是,如果方法名称可以异步运行,请在方法名称后加上前缀:

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

您需要研究有关async更多信息,并await能够正确使用它们。 您可以阅读这篇出色的文章,以了解更多详细信息并获得更好的了解。

GetResponseText不返回string ,而是返回一个Task (它实际上应命名为GetResponseTextAsync )。 您要么需要await该任务,要么WaitResult

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM