我有一个简单的请求函数,用于记录用户。我刚刚学习了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());
}
有关如何使其发挥作用的任何建议?
答案 0 :(得分:2)
绝对最简单的方法是将HttpWebRequest
替换为HttpClient
。
您还希望使用异步方法签名:
public static async Task<string> LogInAsync(string email, string password)