Custom Binding Part 2: Creating a Basic REST Service Using CUSTOM Binding

In this article, I am going to show you how we could create a basic WCF REST service using custom binding. 

Part 1 of this article series could be read here

Follow the steps below, 

Step 1 

Create a new WCF service application project. Delete all the default codes getting created by WCF. 

Step 2

Create the contract, 
 
1.gif
  1. There is only one operation contract. 
  2. Function is returning Message and taking input parameter also as Message type. 
  3. * To ReplyAction says not to add reply action to the message. 
  4. * To Action will add that route all incoming request to this method.
Step 3

Implementing the service.

2.gif
 
  1. Using HTTPRequestMessageProperty class, I am finding absolute path for requesting URL. 
  2. Then I am checking whether request type is GET or not. If type is GET, I am displaying the message body. 
  3. Then I am checking the query string, if query string is there I am displaying that.
  4. Then, I am creating the message. I am giving the message version as none.  And appending a string. This will be displayed in browser as string. 
  5. Using HttpResponseMessageProperty class I am creating the response message.  Then I am adding the custom header.
  6. Then I am returning the response.
Compile the WCF Service application. 

Step 4

Right click on the solution and add new project of the type console application. Right click on console application project and make it as startup project. Add the reference of System.ServiceModel and System.ServiceModel.Channel reference to the console project. 

Step 5: Creating custom binding for REST Service. 

namespace HostingApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomBinding myBinding = new CustomBinding();
            TextMessageEncodingBindingElement msgEncoder = new TextMessageEncodingBindingElement();
            msgEncoder.MessageVersion = MessageVersion.None;
            myBinding.Elements.Add(msgEncoder);
            HttpTransportBindingElement bindingelemt = new HttpTransportBindingElement();
            myBinding.Elements.Add(bindingelemt);
            ServiceHost sh = new ServiceHost(typeof(Service1));
            ServiceEndpoint endpoint = null;
            endpoint = sh.AddServiceEndpoint(typeof(IService1),myBinding ,"Http://localhost:8889/TestHttp");            
            sh.Open();
            Console.WriteLine("REST Service is running");
            Console.WriteLine("Press a Key to close the service");
            Console.ReadKey();
        }
    }
}
  1. I am creating object of CustomBinding class. 
  2. Then adding the binding elements in correct order. 
  3. For the transport adding the HttpTransportElement. Because we need to create a REST service and that follow only Http protocol. 
  4. Creating the service host and adding the endpoints. 
Step 6 

Go ahead and run the Console project. You will be getting the below console window.  

3.gif

Now open the browser and open the URL which you added as address in endpoint in the code.  In my case it is http://localhost:8889/TestHttp

4.gif

5.gif

And now when you see the command prompt you can see the other messages. 

For your reference complete source code is as below , 

IService1.cs 

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

namespace MyService
{  
    [ServiceContract]
    public interface IService1
    {
        [OperationContract(Action = "*", ReplyAction = "*")]
         Message  GetMessage(Message msg);
    }
}

Service1.svc.cs

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

namespace MyService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        public  Message   GetMessage(Message msg)
        {
            HttpRequestMessageProperty httpProps;
            string propName;
            propName = HttpRequestMessageProperty.Name;
            httpProps = msg.Properties[propName] as HttpRequestMessageProperty;
            string uri;
            uri = msg.Headers.To.AbsolutePath;
            Console.WriteLine("Request to {0}", uri);
            if (httpProps.Method != "GET")
            {
                Console.WriteLine("Incoming Message {0} with method of {1}",
                    msg.GetReaderAtBodyContents().ReadOuterXml(),
                    httpProps.Method);
            }
            else
            {
                Console.WriteLine("GET Request - no message body ");
            }
            if (httpProps.QueryString != null)
            {
                Console.WriteLine("QueryString = {0} ", httpProps.QueryString);
            }
            Message respone = Message.CreateMessage(MessageVersion.None, "*", "Simple Response String");
            HttpResponseMessageProperty responseProp = new HttpResponseMessageProperty();
            responseProp.Headers.Add("CustomHeader", "Value");
            return respone;
        }
    }
}

And in console application 

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using MyService;

namespace HostingApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomBinding myBinding = new CustomBinding();
            TextMessageEncodingBindingElement msgEncoder = new TextMessageEncodingBindingElement();
            msgEncoder.MessageVersion = MessageVersion.None;
            myBinding.Elements.Add(msgEncoder);
            HttpTransportBindingElement bindingelemt = new HttpTransportBindingElement();
            myBinding.Elements.Add(bindingelemt);
            ServiceHost sh = new ServiceHost(typeof(Service1));
            ServiceEndpoint endpoint = null;
            endpoint = sh.AddServiceEndpoint(typeof(IService1),myBinding ,"Http://localhost:8889/TestHttp");           
            sh.Open();
            Console.WriteLine("REST Service is running");
            Console.WriteLine("Press a Key to close the service");
            Console.ReadKey();
        }
    }
}

I hope this was useful article. Thanks for reading. 

Up Next
    Ebook Download
    View all
    Learn
    View all