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

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

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

        var result = postTask.Result;
        if (result.IsSuccessStatusCode)
        {
            var readTask = result.Content.ReadAsAsync<UserModel>();
            readTask.Wait();
            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

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 Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^