0

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?

Community
  • 1
  • 1
bachkoi32
  • 1,426
  • 4
  • 20
  • 31

1 Answers1

2

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)
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810