Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Create a WCF RESTful Service

DZone's Guide to

Create a WCF RESTful Service

Use the Windows Communication Foundation (WCF) to develop a powerful, interoperable service-oriented application using SOAP.

· Integration Zone
Free Resource

Learn how API management supports better integration in Achieving Enterprise Agility with Microservices and API Management, brought to you in partnership with 3scale

Overview

WCF

Windows Communication Foundation (WCF) is a distributed technology that provides a single, integrated platform or mode called the service mode to develop distributed applications for Windows. With WCF, powerful and interoperable service-oriented applications can be developed. It is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication and also uses Simple Object Access Protocol (SOAP) messages to exchange information between a service and client.

  • Service Contract
    Service contract is an attribute applied to an interface such as IService1. It describes which operations the client can perform on the services.
  • Operation Contract
    Operation Contract is an attribute applied to methods in interfaces such as IService1. It defines a method in an interface. It defines the input parameters and the return type of a specific Operation in the service.
  • Data Contract
    The DataContract defines which data types are passed to and from the service. It defines a class and the DataMember attribute defines the properties.

REST

Representational State Transfer (REST) is a protocol for exchanging data over a distributed environment. The main idea behind REST is that we should treat our distributed services as a resource and we should be able to use simple HTTP protocols to perform various operations on that resource.

JSON

The JavaScript Object Notation (JSON) data format, or JSON for short, is derived from the literals of the JavaScript programming language. JSON helps us to present and exchange data in a self-descriptive, independent and light way. This data can then be easily consumed and transformed into JavaScript objects.

In most browser-based applications, WCF can be consumed using JavaScript, jQuery, AngularJs and so on. When a client makes a call to WCF, JSON or XML is used as the format of the communication. WCF has the option to send the response in JSON object. This can be configured with the WebGet or WebInvoke attribute and the WebHttpBinding. This allows you to expose a ServiceContract as a REST service that can be invoked using either JSON or plain XML.

  • GET: Retrieves the information. 
  • PUT: Replaces the entire collection with another collection. 
  • POST: Creates a new entry in the collection. 
  • DELETE: Deletes the entire collection. 

First we need to create the WCF REST Service. So use the following procedure.

Open Visual Studio and select "File", then "New" and "Project...". Then select WCF in the left side, click WCF Service Application. Click OK.
IService

Now delete the IService.cs and Service.cs files.

Customer Service

Now right-click on the project in the Solution Explorer and select Add New Item, then select WCF Service and name it Customer Service.

WCF SErvice

Now I will create a Data Contract CustomerDataContract.

Right-click on the project in the Solution Explorer and select Add New Item. Then add a .cs file and use the following code:

class

CustomerDataContract.cs

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Runtime.Serialization;  
using System.Web;  

namespace WCFRESTfulService  
{  
    [DataContract]  
    public class CustomerDataContract  
    {  
        [DataMember]  
        public string CustomerID { get; set; }  
        [DataMember]  
        public string CompanyName { get; set; }  
        [DataMember]  
        public string ContactName { get; set; }  
        [DataMember]  
        public string ContactTitle { get; set; }  
        [DataMember]  
        public string Address { get; set; }  
        [DataMember]  
        public string City { get; set; }  
        [DataMember]  
        public string Region { get; set; }  
        [DataMember]  
        public string PostalCode { get; set; }  
        [DataMember]  
        public string Country { get; set; }  
        [DataMember]  
        public string Phone { get; set; }  
        [DataMember]  
        public string Fax { get; set; }  
    }  
}  

Now it is time to add your database to the application. So create a new folder named Model in your project.

create a new folder

Now right-click on the Model folder and select Add, then click New Item.

Add new item

Select the ADO.NET Entity Data Model.

ADO DOT NETRight-click the Customer entity and choose Generate Database from Model on the context menu. You'll see the Generate Database Wizard dialog box, as shown here:

crate connectionHere click on New Connection then enter your SQL Server Details and then select your database.

Select database

data connection

click finish

model

Now open the ICustomerService.cs file to define an interface as in the following:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Runtime.Serialization;  
using System.ServiceModel;  
using System.ServiceModel.Web;  
using System.Text;  

namespace WCFRESTfulService  
{  
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICustomerService" in both code and config file together.  
    [ServiceContract]  
    public interface ICustomerService  
    {  
        [OperationContract]  
        [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json,  
            ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetAllCustomer/")]  
        List<CustomerDataContract> GetAllCustomer();  

        [OperationContract]  
        [WebGet( RequestFormat = WebMessageFormat.Json,  
           ResponseFormat = WebMessageFormat.Json,  
           UriTemplate = "/CustomerDetails/{CustomerID}")]  
        CustomerDataContract CustomerDetails(string customerID);  
    }  
}  

CustomerService.svc

Code

CustomerService

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Runtime.Serialization;  
using System.ServiceModel;  
using System.Text;  

//  
using WCFRESTfulService.Model;  

namespace WCFRESTfulService  
{  
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CustomerService" in code, svc and config file together.  
    // NOTE: In order to launch WCF Test Client for testing this service, please select CustomerService.svc or CustomerService.svc.cs at the Solution Explorer and start debugging.  
    public class CustomerService : ICustomerService  
    {  
        NorthwindEntities dc;   
        public CustomerService()  
        {  
            dc = new NorthwindEntities();  
        }  
        public List<CustomerDataContract> GetAllCustomer()  
        {  
            var query = (from a in dc.Customers  
                         select a).Distinct();  

            List<CustomerDataContract> CustomersList = new List<CustomerDataContract>();  

            query.ToList().ForEach(x =>  
            {  
                CustomersList.Add(new CustomerDataContract  
                {  
                    CustomerID = Convert.ToString(x.CustomerID),  
                    CompanyName = x.CompanyName,  
                    ContactName = x.ContactName,  
                    ContactTitle = x.ContactTitle,  
                    Address = x.Address,  
                    City = x.City,  
                    Region = x.Region,  
                    PostalCode = x.PostalCode,  
                    Country = x.Country,  
                    Phone = x.Phone,  
                    Fax = x.Fax,                     
                });  
            });  
            return CustomersList;  
        }  

        public CustomerDataContract CustomerDetails(string customerID)  
        {  
            CustomerDataContract Cust = new CustomerDataContract();             
            try  
            {                  
                var query = (from a in dc.Customers  
                             where a.CustomerID.Equals(customerID)  
                             select a).Distinct().FirstOrDefault();  
                Cust.CustomerID = query.CustomerID;  
                Cust.CompanyName = query.CompanyName;  
                Cust.ContactName = query.ContactName;  
                Cust.ContactTitle = query.ContactTitle;  
                Cust.Address = query.Address;  
                Cust.City = query.City;  
                Cust.Region = query.Region;  
                Cust.PostalCode = query.PostalCode;  
                Cust.Country = query.Country;  
                Cust.Phone = query.Phone;  
                Cust.Fax = query.Fax;   
            }  
            catch (Exception ex)  
            {  
                throw new FaultException<string> (ex.Message);  
            }  
            return Cust;  
        }  
    }  
}  

Now make the following changes in your WCF application web.config file:

web config file

Now our WCF REST Service is ready. Run the WCF REST service.

http://localhost:1040/CustomerService.svc/GetAllCustomer/

WCF REST service

You will see the following output http://localhost:1040/CustomerService.svc/GetAllCustomer/

You will see below output

You will see the following output http://localhost:1040/CustomerService.svc/CustomerDetails/ALFKI

output

I hope this article is useful. If you have any other questions then please mention it in the comments section.

Unleash the power of your APIs with future-proof API management - Create your account and start your free trial today, brought to you in partnership with 3scale.

Topics:
wcf data services ,wcf rest api ,.net ,soa

Published at DZone with permission of Sanjay Kumar. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}