In this Post, we’ll see how can we easily write a code for consuming WCF Rest services. There could be many other scenarios where we need to write a test Client application to test WCF Rest services. In this post, we will consume two type of HTTP methods GET and POST. Let’s see one by one
Consume Get Method
Here, We can have a WCF Rest service which is deployed somewhere on web server or at IIS on local machine or even uses Visual Studio integrated web server. In my sample, I am using Visual Studio one. And the URL of that service is
By Default Get method’s input and output parameters are of type XML(default) or JSON and returned in string format. Here the method returns in JSON format. Let’s write the sample
So what all steps we need to perform
1- Create a HTTPWebRequest object with the provided REST service URL
2- Initiate the request and get response
3- Read the stream from the response
4- Serialize the stream and read the result
Let’s jump to the code
So as each line of code is also commented as mentioned in the step. Let’s run it as well
So it is fairly easy to pass a parameter in Get method. It is passed via URL only so it can of type string only.
Also, the REST Services exposed via GET method, can be called and Tested via browser. So to test it via browser, you should browse the complete URL (service url including method name or as URI defined while exposing). Here the method takes no parameter and returns a list of object of custom type.
Now Let’s move to Post method
Consume Post Method
It is not as straight forward as above one. As we know that in the Post method the input is passed in body of request and that should be properly serialized as well. As we know that WCF uses it’s own serialization named as System.Runtime.Serialization so it should be used for serializing the input. If you are using XmlSerializer or other then you might face issue.
Here in my service method, it is taking a custom object type parameter and returning same type as well. The REST method signature looks like
[WebInvoke(Method = "POST", UriTemplate = "/User/GetAllUsersInfo")] UserInformation GetUserDetails(UserInformation user);
And the service URL would be like
Here we need to have some more steps while calling this service. the steps are like
1- Create a HTTPWebRequest object with the provided REST service URL.
2- Provide the method type and Content Type to the request.
3- Create the input object and serialize it and then assign that stream the request.
4- Initiate the request and get response.
5- Read the stream from the stream and deserialize the stream into the object
Let’s see the code
The code is self explanatory and commented as well .Here some of the key things to keep in mind that How the input object is serialized and assigned to the body of the request and similarly reading the response from the response. The code is
Hope you all have enjoyed the post. Thank you all.