In our previous articles, we understood:
Let’s create a WCF rest service.
Step 1: Create a WCF service project
- Open Visual Studio.
- From File -> New Project. Select WCF from left and create a new WCF Service Application and give the name as MYRestService.
Step 2: Define Data Contract
- Now add a class to newly created project. Name it to Product.cs.
- Define the data contract in product.cs
- We wil Prepare the data source in class without fetching from database
Step 3: Define Service Contract
- Now add a new WCF Service named ProductRestService.svc to this project
- It will add contract as well as service file to project
- There is one method in service. Most important is the 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.
Step 4: Implementing Service
- Only one method GetProductList is defined in the contract, so implementing service class will be as follows:
Step 5: Configure service and Behavior
- Below is the complete ServiceModel configuration settings.
webHTTPBinding is the binding used for RESTful services.
Let’s test the restful service:
- Right click ProductRESTService.svc file and click “View in Browser“
- 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.
- Modify the URL in browser and add “GetProductList/” to it. So, this is the UriTemplete we defined as service contract method.
Reference books, you may like:Programming WCF Services: Design and Build Maintainable Service-Oriented Systems
WCF Multi-Layer Services Development with Entity Framework, 4th Edition
Learning WCF: A Hands-on Guide
© 2015, admin. All rights reserved.