Imagine you have a web service. The web service is configured to use the POST method and it’s configured to accept JSON requests and responses. The web service accepts a ‘Product’ object as the input parameter. The web service simply gets the ‘Name’ attribute of the ‘Product” and returns it as a string. I know that this web service is useless, but it works as a simple example.

Here is the definition for the ‘Product’ class. You need to create a ‘Product.cs’ class in the project where the ‘CallService<T>’ method is being called:

public class Product{

public int ID { get; set; }
public string Name { get; set; }

}

You need to add the following references to your project and add the following code at the top of the file where ‘CallService<T>’ is defined:

using System;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

Here is the definition of the ‘CallService<T>’ method:

// <T> needs to specify the return type of the web service
public T CallService<T>(string webServiceUrl, object param){

object result = new object(); //this is the object that will be returned by CallService<T>
string jsonString = new JavaScriptSerializer().Serialize(param); //get Json string representation of object
//Console.WriteLine(jsonString); //display the json encoded string (if you are using a console application)

byte[] postData = Encoding.UTF8.GetBytes(jsonString); //convert the Json string to an array of bytes
WebRequest request = WebRequest.Create(webServiceUrl); //create a request object
request.Method = “POST”; //we will use POST (as opposed to GET)
request.ContentLength = postData.Length; //set the length of the request
request.ContentType = “text/json”; //we will use Json data formatting
using (Stream reqStream = request.GetRequestStream()) {

reqStream.Write(postData, 0, postData.Length); //send the input data to the web service

}
using (WebResponse response = request.GetResponse()) {

string jsonResult = new StreamReader(response.GetResponseStream()).ReadToEnd(); //get the Json string from the web service response
result = new JavaScriptSerializer().Deserialize<T>(jsonResult); //convert the Json string to a c# object of type T, then cast it as an object

}
return (T)result;

}

Here is an example call. Please note that you need to change ‘<string>’ so that it matches the return type of your web service:

Product inputParameter = new Product();
inputParameter.ID = 123;
inputParameter.Name = “Laptop”;

string url = “http://localhost:49269/MyService.svc/GetProductName “;

string outputParameter = CallService<string>(url, inputParameter);

 

Advertisements