How to convert http Web Request to asynchronous re

2019-01-29 10:17发布

问题:

I have a simple request function that logs a user in. I just learned about aysnc method (I am a C# beginner) and saw that requests can be made using async and await. But I am having a hard time figuring out how to convert my existing code. I read similar questions on stackoverflow but still haven't been able to make it work with my code.

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

Any suggestions on how would I make it work?

回答1:

The absolute easiest way is to replace HttpWebRequest with HttpClient.

You'll also want to use an asynchronous method signature:

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