Mar 19, 2013

.NET HttpClient synchronous POST & GET

How to consume  ASP.NET REST-full WEB API in .NET Windows forms client app?
Visual Studio 2012 has introduced async methods and Tasks etc.
Hence it took me some effort to Google-out and figure out correct and cleanest way to POST & GET some POCO to ASP.NET WEB API and return it.

Class System.Net.Http HttpClient has gone through revamping and is ASYNC ready. Therefore it was hard to figure out simple stuff.

Bellow are two generic methods that perform converting POCO to Json using Json.NET framework and POST it to ASP.NET WEB API service. There is also simple GET variant.

Magic word  when using ASYNC methods is property Result.
It instructs method basically to switch to SYNCHRONOUS mode dropping all Task, await etc. stuff.

Yes, this approach negates whole async model of these methods.


using System.Net.Http;
using Newtonsoft.Json;

    public TResponse Post<TResponse, TRequest>(TRequest postdata, string postUrl)            
        {
            using (HttpClient client = new HttpClient())
            {
                var postdataJson = JsonConvert.SerializeObject(postdata);
                var postdataString = new StringContent(postdataJson, new UTF8Encoding(), "application/json");
                var responseMessage = client.PostAsync(postUrl, postdataString).Result;
                var responseString = responseMessage.Content.ReadAsStringAsync().Result;
                return JsonConvert.DeserializeObject<TResponse>(responseString);
            }
        }

        /// <summary>
        /// Perform HTTP Get the specified post ASP.NET WEB API URL.
        /// Try to convert response to TResponse
        /// </summary>
        /// <typeparam name="TResponse">The type of the response.</typeparam>
        /// <param name="postUrl">The post URL.</param>
        /// <returns></returns>
        public TResponse Get<TResponse>(string postUrl)
        {
            using (HttpClient client = new HttpClient())
            {
                var responseMessage = client.GetStringAsync(postUrl).Result;
                return JsonConvert.DeserializeObject<TResponse>(responseMessage);
            }
        }




Links:
http://forums.asp.net/t/1773007.aspx/1/10
http://blogs.msdn.com/b/webdev/archive/2012/08/26/asp-net-web-api-and-httpclient-samples.aspx

5 comments:

  1. Thank you, this was helpful

    ReplyDelete
  2. Just note this is not thread-safe and can deadlock (and almost certainly will if you are running this code in a website).

    ReplyDelete
    Replies
    1. I knew it... So, do you know how to make it SAFE from deadlocks, and still synchronous? I DON'T want it to be thread-safe by the way - I want to make it act like it's being executed on the UI thread (even though it's not).

      Delete