Calling Web API Using HttpClient

How To Consume REST API in C#.NET using HttpClient | .Net Core

HttpClient class provides a base class for sending/receiving the HTTP requests/responses from a URL. It’s supported to the async feature of .NET framework.

The HttpClient is able to process multiple concurrent requests. It’s a layer over HttpWebRequest and HttpWebResponse.

All methods with HttpClient are asynchronous.

Example for making a Get/POST Request,
    var encriptedUserLogin = "hijksds@34dff@556";
    var encriptedPwd = "jsdjhll!23392mf544134";

    //GET CALL
    string apiURL = "http://localhost:62028/api/Users/Authenticate";
    UriBuilder builder = new UriBuilder(apiURL);                       
    builder.Query = "Username="+ encriptedUserLogin + "&Password="+ encriptedPwd + "";

    using (var client = new HttpClient())
        HttpResponseMessage response = client.GetAsync(builder.Uri).Result;
        if (response.IsSuccessStatusCode)
            UserModel userResult = response.Content.ReadAsAsync<UserModel>().Result;                               

    using (var client1 = new HttpClient())
        var userDataModel = new UserModel() { Username = encriptedUserLogin, Password = encriptedPwd };

        var postTask = client1.PostAsJsonAsync<UserModel>(apiURL, userDataModel);

        var result = postTask.Result;
        if (result.IsSuccessStatusCode)
            var readTask = result.Content.ReadAsAsync<UserModel>();
            var userRes = readTask.Result;

Model Class,
    public class UserModel
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string Token { get; set; }


Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog -
My Books - Book 1 and Book 2

How To Consume REST API in C#.NET using HttpClient | .Net Core How To Consume REST API in C#.NET using HttpClient | .Net Core Reviewed by Anil Singh on 8:31 AM Rating: (5) Powered by Blogger.