none
Http object for calling webapi post, get and put methods RRS feed

  • Question

  • HI ,

    I need to consume a webapi from the windows form application , I can see that the http client is the latest one in .net framework.

    I can see only the async method, not able to see any normal (non- asynchronous) methods.

    can you please suggest which is better for making asynchronous and non- asynchronous api calls, I need the non-asynchrous calls specifically.

    is it webclient , httpclient or  restsharp client  or any .other 

    I need a client which is not obsolete and can be used for future.

    Can you please advice me on this .

    thanks


    • Edited by techasuran Sunday, February 16, 2020 10:39 PM
    Friday, February 14, 2020 6:56 AM

All replies

  • Hi techasuran,
    Base on your description, I find some related documents and you can refer to it.
    [HTTP Operations GET, POST, PUT and DELETE From .NET Client]
    [How to Implement POST Method in Web API]
    [Using HTTP Methods (GET, POST, PUT, etc.) in Web API]
    Hope these are helpful for you.
    Note: This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; Therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, February 17, 2020 7:06 AM
  • Did you even read the documentation?  The doc page for HttpClient shows how to this.  As soon as you use "await", an asynchronous task becomes synchronous.

         HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
         response.EnsureSuccessStatusCode();
         string responseBody = await response.Content.ReadAsStringAsync();



    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Monday, February 17, 2020 7:42 AM
  • Here is an example of using the HTTPClient()

    using Entities;
    using System.Collections.Generic;
    
    namespace ServiceLayer
    {
        public interface IPayRollSvc
        {
            List<DtoPayroll> GetAll();
            DtoPayroll Find(int id);
            DtoPayroll FindPayRollByAuthorId(int id);
            void Add(DtoPayroll dto);
            void Update(DtoPayroll dto);
            void Delete(DtoId dto);
        }
    }
    ==========================================================
    using Entities;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    
    namespace ServiceLayer
    {
        public class PayRollSvc :IPayRollSvc
        {
            public List<DtoPayroll> GetAll()
            {
                var dtopayrolls = new List<DtoPayroll>();
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://localhost/WebAPI/api/payroll/GetAll");
    
                    var response = client.GetAsync(uri).Result;
    
                    if (!response.IsSuccessStatusCode)
                        throw new Exception(response.ToString());
    
                    var responseContent = response.Content;
                    var responseString = responseContent.ReadAsStringAsync().Result;
    
                    dynamic payrolls = JArray.Parse(responseString) as JArray;
    
                    foreach (var obj in payrolls)
                    {
                        DtoPayroll dto = obj.ToObject<DtoPayroll>();
    
                        dtopayrolls.Add(dto);
                    }
                }
    
                return dtopayrolls;
            }
            public DtoPayroll Find(int id)
            {
                DtoPayroll dto;
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://localhost/WebAPI/api/payroll/Find?id=" + id);
                    HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result;
    
                    if (!getResponseMessage.IsSuccessStatusCode)
                        throw new Exception(getResponseMessage.ToString());
    
                    var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result;
    
                    dynamic payroll = JsonConvert.DeserializeObject(responsemessage);
    
                    dto = payroll.ToObject<DtoPayroll>();
                }
    
                return dto;
            }
    
            public DtoPayroll FindPayRollByAuthorId(int id)
            {
                DtoPayroll dto;
    
                using (var client = new HttpClient())
                {
                    var uri = new Uri("http://localhost/WebAPI/api/payroll/FindPayRollByAuthorId?id=" + id);
                    HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result;
    
                    if (!getResponseMessage.IsSuccessStatusCode)
                        throw new Exception(getResponseMessage.ToString());
    
                    var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result;
    
                    dynamic payroll = JsonConvert.DeserializeObject(responsemessage);
    
                    dto = payroll.ToObject<DtoPayroll>();
                }
    
                return dto;
            }
    
            public void Add(DtoPayroll dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("WebAPI/api/payroll/Add", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
    
            public void Update(DtoPayroll dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("WebAPI/api/payroll/Update", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
    
            public void Delete(DtoId dto)
            {
                using (var client = new HttpClient { BaseAddress = new Uri("http://localhost") })
                {
                    string serailizeddto = JsonConvert.SerializeObject(dto);
    
                    var inputMessage = new HttpRequestMessage
                    {
                        Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json")
                    };
    
                    inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage message =
                        client.PostAsync("WebAPI/api/payroll/Delete", inputMessage.Content).Result;
    
                    if (!message.IsSuccessStatusCode)
                        throw new Exception(message.ToString());
                }
            }
        }
    }
    

    Monday, February 17, 2020 8:15 AM
  • HttpClient is the preferred type to use for HTTP calls. Use `WebClient` only in the cases where you might want to screen scrape as it is a little easier. However using `HttpClient`comes with the need to understand how it works. The first mistake that is generally made is that it is created/disposed in code. You will almost never dispose of this client. Doing so frequently will result in eating up the sockets that are available. Therefore every app is built to have a single `HttpClient` instance for each remote URL you will connect to. DO NOT create/dispose this instance each time.

    If your app is dependency injection aware then inject the `HttpClient` into your higher level code. Configure the DI to create a single instance of this client. Note that once created and the first call is made you cannot change the URL or default headers. This is by design and correct. The URL is the root URL to the service, not to the resource under that URL. The resource is passed as part of the GetAsync/... methods. If you need to pass additional headers to some calls then you use the raw `HttpRequestMessage` and use `SendAsync`. `HttpClient` is thread safe and therefore can be used by any # of threads at the same time. 

    If your app is not DI aware then create a static instance of the client and pass it to your higher level code. .NET Core has this type built in but for .NET Framework a simple static class works. Otherwise the behavior is the same.

    //High level service used in code
    public class UserService
    {
       public UserService ( HttpClient client )
       {
          _client = client;
       }
    
       //Ignoring cancellation here...
       public async Task<User> GetUsersAsync ( )
       {
           //Pass resource to client
           using (var response = await _client.GetAsync("users").ConfigureAwait(false))
           {
              response.EnsureSuccessStatusCode();
    
              //Get data from content (generally JSON)
              ...
           };
       }
    
       private readonly HttpClient _client;
    }
    
    //Poor man's DI
    public static class HttpClientFactory
    {
       //Would probably be better to create client on the first call but this requires more code...
       public static void AddClient ( string name, HttpClient client )
       {
          _clients[name] = client;
       }
    
       public static HttpClient GetClient ( string name )
       {
          return _clients[name];
       }
    
       private static readonly Dictionary<string, HttpClient> s_clients = new Dictionary<string, HttpClient>(StringComparer.OrdinalIgnoreCase);
    }
    
    //App startup, no DI
    var client = new HttpClient("https://myservice.tempuri.org");
    HttpClientFactory.AddClient("MyService", client);
    
    //To create the higher level service in code
    var service = new UserService(HttpClientFactory.GetClient("MyService"));


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, February 17, 2020 5:39 PM
    Moderator