Advertisement
Guest User

C# HTTP request

a guest
May 23rd, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.22 KB | None | 0 0
  1. // Install Newtonsoft.Json NuGet package and put "using Newtonsoft.Json;" in the beginning of the file
  2. public static async Task<bool> HttpRequest(string email, string password)
  3. {
  4.     string loginJson = JsonConvert.SerializeObject(new { Email = email, Password = password});
  5.     StringContent content = new StringContent(loginJson, Encoding.UTF8, "application/json");
  6.     HttpResponseMessage result = await client.PostAsync("http://localhost:64854/api/logins", content);  // check the port number after starting the API server
  7.  
  8.     if (result.IsSuccessStatusCode)
  9.     {
  10.         string response = await result.Content.ReadAsStringAsync();
  11.         Debug.WriteLine(response);
  12.  
  13.         // If you copy the Login model from the API project, you can parse the response into an object:
  14.         // Login loginDetails = JsonConvert.DeserializeObject<Login>(response);
  15.  
  16.         return true;
  17.     }
  18.     else
  19.     {
  20.         return false;
  21.     }
  22. }
  23.  
  24. public async void LoginMethod()
  25. {
  26.     try
  27.     {
  28.         bool isSuccess = Task.Run(async () => await HttpRequest(Email, Password)).Result;
  29.         Debug.WriteLine($"Is login succeeded: {isSuccess}");
  30.     }
  31.     catch (AggregateException ex)
  32.     {
  33.         Debug.WriteLine(ex);
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement