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

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

Silent Renew and the "login_required" Error When Using oidc-client