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
http://localhost:26944/Service1.svc/User/GetAllUsers
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
http://localhost:26944/Service1.svc//User/GetAllUsersInfo
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.
Cheers,
Brij
Nice Article.
Pingback: TechNet Blogs
Do we need to post add the Service Reference of the REST Service ? Do we need to create the UserInformation class i the client side also ?
The main use of REST services are to call from Client side and it is return in JSON format nowadays. So at client side, you don’t need know the type exactly and you can read the information easily using Javascript object but its better to know the format, it helps.
I have try this solution, the get part works fine, but the post give me this error 400 Bad request.
Is your service properly configured? Can you also share your code that how are you consuming?
string body;
var url = SharedClassRepository.GetProductListUrl + “/GatProductCategoryList”;
var request = (HttpWebRequest)WebRequest.Create(string.Format(url));
request.Method = “POST”;
request.ContentType = @”text/xml;charset=utf-8″;
var dataContractSerializer = new DataContractSerializer(typeof(validUserRequestContract));
var validUserRequestContract = new validUserRequestContract { LoginId = SharedClassRepository.LoginId, Password = SharedClassRepository.Password };
using(var memoryStream = new MemoryStream())
using (var reader = new StreamReader(memoryStream))
{
dataContractSerializer.WriteObject(memoryStream, validUserRequestContract);
memoryStream.Position = 0;body = reader.ReadToEnd();
}
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(body);
}
var response = request.GetResponse();
var stream = response.GetResponseStream();
var result = (GatProductCategoryListResult)dataContractSerializer.ReadObject(stream);
This is my code for Post Operation but it gives me error 400 bad request
It seems the request is not correct. Also from the URL, it seems it should be get request. Did you try to test your service using Fiddler/Postman? First test this then consume in C#. Do check the contenttype as well.
i have test this with wcf test client and i passed loginid and password in it
and it gives me response in xml.