RESTful services are those which follow the REST (Representational State Transfer) architectural style. Before implementing your first RESTful service, lets first understand the concept behind it. As we know that WCF allows us to make calls and exchange messages using SOAP over a variety of protocols i.e. HTTP, TCP, Named Pipes and MSMQ etc. In a scenario, if we are using SOAP over HTTP, we are just utilizing HTTP as a transport. But HTTP is much more than just a transport. So, when we talk about REST architectural style, it dictates that “Instead of using complex mechanisms like CORBA, RPC or SOAP for communication, simply HTTP should be used for making calls”.
::::: Practical Guide To WCF RESTful Service :::::
RESTful architecture use HTTP for all CRUD operations like (Read/Create/Update/Delete) using simple HTTP verbs like (GET, POST, PUT, and DELETE).It’s simple as well as lightweight. For the sake of simplicity, I am going to implement only a GET request for which service will return certain types of data (i.e. Product data) in XML format.
- Create a WCF Service Project.
- Preparing the data (e.g. Product) to return
- Creating Service Contract
- Implementing Service
- Configure Service and Behavior
You can download the complete source code for this article here.
- Open Visual Studio.
- From File -> New Project. Select WCF from left and create a new WCF Service Application.
2. Preparing the data to return
- Now add a class to newly created project. Name it to Products.cs.
3. Creating Service Contract
It will add contract as well as service file to project. Following is the code for service contract i.e. IProductRESTService.cs.
IProductRESTService contains only one method i.e. GetProductList. Important points to understand about this method is WebInvoke attribute parameters.
- Method = “GET”, represents an HTTP GET request.
- ResponseFormat = WebMessageFormat.Xml, response format will be XML here but we can return JSON as well by changing its value to WebMessageFormat.json.
- BodyStyle = WebMessageBodyStyle.Bare, indicates neither the request and nor response are wrapped. Other possible values for BodyStyle are Wrapped, WrappedRequest, WrappedResponse.
- UriTemplate = “GetProductList/”, it has two parts, URL path and query.
Don’t forget to add using System.ServiceModel.Web at top.
4. Implementing RESTful Service
In this step we are going to implement the service. Only one method GetProductList is defined in the contract, so implementing service class will be as follows:
5. Configure Service and Behavior
The last step is to configure the service and its behaviors using the configuration file. Following is the complete ServiceModel configuration settings.
<services>
Right click ProductRESTService.svc file and click “View in Browser“. You will see the following screen, that means service is fine.
An important point to consider here is that in Service Behavior Configuration, we have setted httpGetEnabled=”true” for serviceMetadata that’s why we are getting above service screen with wsdl option.
This is what we do normally for SOAP-based services. REST-based services only uses HTTP verbs on a resource, so we can disable WSDL in this case by simply setting httpGetEnabled=”false”. Now if we run the service again, we will get the following screen.
Just modify the URL in browser and add “GetProductList/” to it. So, this is the UriTemplete we defined as service contract method.
Hopefully, this simple WCF tutorial will be helpful for the readers. To keep the things simple, I restrict it to just getting records using HTTP GET verb. But you can find a complete implementation for all CRUD (Create, Read, Update, Delete) operations using RESTful service in another WCF RESTful Service tutorial here.
Top 10 Interview Questions and Answers Series:
- Top 10 WCF Interview Questions
- Comprehensive Series of WCF Interview Questions
- Top 10 HTML5 Interview Questions
- Top 10 ASP.NET Interview Questions
- Comprehensive Series of ASP.NET Interview Questions
- Top 10 ASP.NET MVC Interview Questions
- Top 10 ASP.NET Web API Interview Questions
- Top 10 ASP.NET AJAX Interview Questions
- Top 20 AngularJS Interview Questions
- a Must Have SharePoint Interview Questions
public static string PostServiceRequest(string url, string JSONFilter)
{
string result = string.Empty;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = “text/json”;
httpWebRequest.Method = “POST”;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(JSONFilter);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
save time thanks
worked right away. thanks.
Thanks for this Tutorial , how can i pass a parameter before i can get the data in this tutoral and how can i make my Restful WCF Service
Explaination is good here too, but Code at this link works fine with same easy steps as here but with working result
Good explanation
Why does my REST service created throught this method has a wsdl ? I was under the impression that RESt services wouldnt have a wsdl . The Url for REST works fine and I’m able to see the XML output . Yet when i put the url with ?wsdl it shows up ….
Running into a problem with:
public List ProductList
The error states: Using the generic type ‘System.Collections.Generic.List’ requires 1 Type argument.
Hi jrobinson,
I have updated this WCF Tutorial to resolve the issue for certain versions. You can follow the steps to have a clean implementation for WCF RESTful service.
Hopefully, I’ll upload source code for the implementation shortly, so you will have a Visual Studio solution with complete source of the project.
Thanks for your valuable feedback.
Regards,
Imran
how can i do this using xml data, pls help me
Can you please elaborate your question? As it’s already using xml as response to render XML data.
Please see the service contract as:
ResponseFormat = WebMessageFormat.Xml
Yes, How can i pass the xml data to service in PUT or POST Method which means RequestFormat = WebMessageFormat.Xml
I know how to call the service using jquery ajax call and pass the json datas, but don’t know how to pass the xml values.
Is it possible to pass the xml datas to service using jquery or any other language should i use ?
yes it’s possible with following piece of sample code.
———————————————————
string postData = SampleXml.ToString();
// convert xmlstring to byte using ascii encoding
byte[] data = encoding.GetBytes(postData);
// declare httpwebrequet wrt url defined above
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
// set method as post
webrequest.Method = “POST”;
// set content type
webrequest.ContentType = “application/x-www-form-urlencoded”;
// set content length
webrequest.ContentLength = data.Length;
// get stream data out of webrequest object
Stream newStream = webrequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
// declare & read response from service
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
——————————————————–
This answer is available at following URL.
http://stackoverflow.com/questions/19906692/how-to-send-xml-via-post-with-wcf
Thank you for your valuable answer, i have already tried this code, but still i m getting 400 bad request error..
thanks a lot
this dont work
public List ProductList
{
get { return products; }
}
bryan,
Can you please explain what doesn’t work for you. What error you’re getting?
Hi Bryan,
Was this question answered?
It’s resolved now and updated.
Nice explained…
Thanks Dude.
Give me one more table class like Order,
Combining both Products and Orders classes data want to get,
How can i do?
please give that example
Dear Anil,
I’ll do the above mentioned in later tutorial here. We come up with a complete example. Please revisit or just register by email.
Create a class as below format:
public class PostAlbumListRequest
{
public List Album { get; set; }
public User User { get; set; }
public string UserToken { get; set; }
}
[OperationContract]
[WebInvoke(Method = “POST”, UriTemplate = “PostAlbum”,
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
PostAlbumResponse PostAlbum(PostAlbumRequest request);
var album = {
AlbumName: “PowerAge”,
Entered: “1/1/1977”
}
var user = {
Name: “Rick”
}
var userToken = “sekkritt”;
$.ajax(
{
url: “http://localhost/Rest/RestServiceImpl.svc/PostAlbum”,
type: “POST”,
contentType: “application/json”,
data: JSON.stringify({ Album: album, User: user, UserToken: userToken }),
success: function (result) {
alert(result.Result);
}
});
Very helpful for WCF beginers!
Hi,
Using VS 2013 Express
Created WCF Service Application project
Works great…
thanks
Let me clear one thing as I mentioned in post step 1. You will create a new project using template “WCF Service Application”. Later in Step 3, you right click your project and add a new “WCF Service” to it.
Hi,
I’m using VS2012. The WCF tab when creating a new project has; WCF Service Library, WCF Service application, WCF workflow service application & sysndication service libray.
This is using the .net framework 4.
David,
WCF Service or WCF Service Application template are available. I am not sure which version of Visual Studio you are using…
Just use WebApi…
The code is missing
[ServiceContract] attribute
public interface IProductRESTService { [OperationContract
Yeah, I missed that. thanks.
Metadata publishing for this service is currently disabled
Dear,
Please verify you follow the step 5. Please confirm following in your configuration file.
serviceMetadata httpGetEnabled=”true”
Using WebApi is way much easier!
WebAPI is another way of doing the same. You can find almost same in Web API at http://www.webdevelopmenthelp.net/2013/09/ASP-Web-API-Service.html
i agree that web api is easier but this can be helpful if your org dont have enough fundings to upgrade to iis 7 or iis 8.