如何使用async和await将http Web请求转换为异步请求

时间:2013-08-06 19:11:20

标签: c# multithreading visual-studio httpwebrequest async-await

我有一个简单的请求函数,用于记录用户。我刚刚学习了aysnc方法(我是一个C#初学者),并看到可以使用async和await进行请求。但我很难搞清楚如何转换现有代码。我在stackoverflow上阅读了similar questions,但仍然无法使用我的代码。

public static string LogIn(string email, string password)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost");
    request.Method = "POST"
    request.ContentType = "application/json";
    request.CookieContainer = cookies;
    CredentialClass credentials = new CredentialClass();
    credentials.email = email
    credentials.password = password;
    var ser = new DataContractJsonSerializer(typeof(CredentialClass));
    ser.WriteObject(request.GetRequestStream(), credentials);
    var response = (HttpWebResponse)request.GetResponse();
    return (response.StatusCode.ToString());
}

有关如何使其发挥作用的任何建议?

1 个答案:

答案 0 :(得分:2)

绝对最简单的方法是将HttpWebRequest替换为HttpClient

您还希望使用异步方法签名:

public static async Task<string> LogInAsync(string email, string password)