A Generic Method for Consuming Data From RESTful WCF Service Methods

I recently added some new methods to an existing RESTful WCF service and needed to consume these methods from an application which had not previously made use of this service. To make this easier, I created the following generic method. It could probably use a little refinement (specifically some code to handle what happens if an attempt is made to cast the service method result to an incorrect type), but it does the trick.

using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
 
namespace RESTService.Helpers
{
    public static class RESTServiceHelpers
    {
        public static T GetResultFromRESTServiceMethod<T>(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 
            request.KeepAlive = true;
            request.Method = "GET";
 
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
 
                Encoding encoding = System.Text.Encoding.GetEncoding(1252);
                Stream responseStream = response.GetResponseStream();
 
                if (responseStream != null)
                {
                    using (StreamReader reader = 
                        new StreamReader(responseStream, encoding))
                    {
                        DataContractSerializer serializer = 
                            new DataContractSerializer(typeof(T));
                        var obj = serializer.ReadObject(responseStream);
                        reader.Close();
                        response.Close();
                        return (T)obj;
                    }
                }
 
                response.Close();
            }
 
            return default(T); //Still here? Return a default value.
        }
    }
}

Comments

Popular posts from this blog

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

"$.ajax is not a function" Error When Using jQuery and Darren Johnstone's ASP.NET Upload/Download Module v2