Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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,
    varencriptedUserLogin = "[email protected]@556";
    varencriptedPwd = "jsdjhll!23392mf544134";

    //GET CALL
    stringapiURL = "http://localhost:62028/api/Users/Authenticate";
    UriBuilder builder = newUriBuilder(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().Result;                               
        }
    }

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

        varpostTask = client1.PostAsJsonAsync(apiURL, userDataModel);
        postTask.Wait();

        varresult = postTask.Result;
        if(result.IsSuccessStatusCode)
        {
            varreadTask = result.Content.ReadAsAsync();
            readTask.Wait();
            varuserRes = readTask.Result;
        }
    }

Model Class,
    public class UserModel
    {
        public intId { get; set; }
        public stringFirstName { get; set; }
        public stringLastName { get; set; }
        public stringUsername { get; set; }
        public stringPassword { get; set; }
        public stringToken { get; set; }
    }

Share the post

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

×

Subscribe to Angular 2 Javascript Asp.net C# Sql Server Knockoutjs Angularjs Kendo Ui Html 5 Web Api Wpf Wcf Etc.

Get updates delivered right to your inbox!

Thank you for your subscription

×