X
25Mar

WCF SOAP and REST Services

WCF (Windows Communication Foundation) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. WCF provides a common platform for all .NET communication.

WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types. So what is SOAP and REST?

What is SOAP?

SOAP (Simple Object Access Protocol) is a simple solution for interaction of different applications built in different languages and running on different platforms as it uses HTTP as its transport and XML as its payload for sending and receiving messages. It is a lightweight and a loosely coupled protocol for exchange of information in a decentralized and a distributed environment.

What is REST?

REST (Representational State Transfer), attempts to codify the architectural style and design constraints that make the Web what it is. REST emphasizes things like separation of concerns and layers, statelessness, and caching, which are common in many distributed architectures because of the benefits they provide. These benefits include interoperability, independent evolution, interception, improved scalability, efficiency, and overall performance."

Actually only the difference is how clients access our service. Normally, a WCF service will use SOAP, but if you build a REST service, clients will be accessing your service with a different architectural style (calls, serialization like JSON, etc.).

Exposing a WCF service with both SOAP and REST endpoints, requires just a few updates to the codebase and configuration. But first, let’s start from the beginning.

So how to enable both SOAP and REST services in the same WCF service.

STEP 1: Create a new WCF service application.

STEP 2:   Let us create two service contracts . One for SOAP and one for REST Service. I have created a Service Contract IService1 for SOAP and Service Contract IService2 for REST as shown below,

 

IService1.cs

[ServiceContract]

    public interface IService1

    {

        [OperationContract]

        List<Customers> GetCustomers();

        [OperationContract]

        void Add(Customers cust);

    }   

 

    public class Customers

    {

        public int CustomerID { get; set; }

        public string CustomerName { get; set; }

        public string CustomerCity { get; set; }

    }

 

IService2.cs

[ServiceContract]

    public interface IService2

    {

        [OperationContract]

        [WebGet(UriTemplate = "/GetCustomer", RequestFormat = WebMessageFormat.Json,

        ResponseFormat = WebMessageFormat.Json)]

        List<Customers> GetCustomers();

    }

 

STEP 3:  Implementing both SOAP and REST service i.e. IService1 and IService2 in Service1.svc file.Add below code in Service1.svc

    public class Service1 : IService1, IService2

    {

      List<Customers> lstCustomers = new List<Customers>();

        public void Add(Customers cust)

        {

            lstCustomers.Add(cust);

        }

        public List<Customers> GetCustomers()

        {

            lstCustomers.Add(new Customers { CustomerID = 1, CustomerName = "praveen", CustomerCity = "bangalore" });

            return lstCustomers;

        }

    }

 

STEP 4:  Configuring WebConfig file

Configure service for both basicHttpBinding and webHttpBinding, So in Web.Config file define two endpoints - one each for SOAP and REST. The binding for SOAP is basicHttpBinding and for REST is webHttpBinding. Also define ServiceBehavior for publishing metadata for SOAP endpoint so that the client application can consume the WCF service. Add this below code in web config.

 

xml version="1.0"?>

<configuration>

  <appSettings>

    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

  appSettings>

  <system.web>

    <compilation debug="true" targetFramework="4.5" />

    <httpRuntime targetFramework="4.5"/>

  system.web>

  <system.serviceModel>

    <behaviors>

      <serviceBehaviors>

        <behavior name="servicebehavior">

         

          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>

         

          <serviceDebug includeExceptionDetailInFaults="false"/>

        behavior>

      serviceBehaviors>

      <endpointBehaviors>

        <behavior name="restbehavior">

          <webHttp/>

        behavior>

      endpointBehaviors>

    behaviors>

    <services>

      <service name ="RESTvsSOAP.Service1"

               behaviorConfiguration ="servicebehavior">

        <endpoint name ="SOAPEndPoint"

                  contract ="RESTvsSOAP.IService1"

                  binding ="basicHttpBinding"

                  address ="soap" />

        <endpoint name ="RESTEndPoint"

                  contract ="RESTvsSOAP.IService2"

                  binding ="webHttpBinding"

                  address ="rest"

                  behaviorConfiguration ="restbehavior"/>

      service>

    services>

    <protocolMapping>

      <add binding="basicHttpsBinding" scheme="https" />

    protocolMapping>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

  system.serviceModel>

  <system.webServer>

    <modules runAllManagedModulesForAllRequests="true"/>

   

    <directoryBrowse enabled="true"/>

  system.webServer>

configuration>

 

STEP 5: Consuming the services

  To consume the WCF service in the same solution, add a new project, name it as ‘ConsumingServices’. In this project, add the service reference of the WCF service using the following address:

http://localhost:62333/Service1.svc

In program.cs file add below code

        static void Main(string[] args)

        {

            CallingSOAPfunction();

            CallingRESTfunction();

        }

        static void CallingSOAPfunction()

        {

            Service1Client proxy = new Service1Client();

            List<Customers> lstCustomer = proxy.GetCustomers();

            foreach (var customers in lstCustomer)

            {               

                Console.WriteLine("CustomerId : " + customers.CustomerID);

                Console.WriteLine("CustomerName : " + customers.CustomerName);

                Console.WriteLine("CustomerCity : " + customers.CustomerCity);

                Console.ReadLine();

            }

        }

 

        static void CallingRESTfunction()

        {

             HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:62333/Service1.svc/Rest/GetCustomer");

            //Get the Web Response

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();

            //Seting Up the Stream Reader

            StreamReader readerStream = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));

            string json = readerStream.ReadToEnd();

            readerStream.Close();

            var jo = JObject.Parse(json.Replace("[", "").Replace("]", ""));

            Console.WriteLine("CustomerId : " + (string)jo["CustomerID"]);

            Console.WriteLine("CustomerName : " + (string)jo["CustomerName"]);

            Console.WriteLine("CustomerCity : " + (string)jo["CustomerCity"]);

            Console.ReadLine();

        }

 SO exposing a WCF service as REST and SOAP, you can make it more accessible to all types of clients. This is especially useful for the clients who can consume the proxy as well as can understand only HTTP communication with XML data processing.

Related

What are Frames? How to handle frames in Selenium WebDriver with C#?

IFrame (FullForm: Inline Frame) is an HTML document that is included in another HTML document and is...

Read More >

What is Synchronization? Handling Synchronization in Selenium WebDriver using C#:

Synchronization meaning: when two or more components involved to perform any action, we expect these...

Read More >

Sending Test reports by Email using Office 365, Gmail

Wouldn’t it be great if Test Report are sent automatically across team as soon the Test Execut...

Read More >

ASP.NET: Audit Trail Implementation using Entity Framework

When you are working with certain projects which involves the Customer records, you might need to tr...

Read More >

Create Restful service using Web API

What is Asp.Net Web API?Asp.Net Web API is a framework for building HTTP services that can be consum...

Read More >

Create custom project templates in Visual Studio

Visual studio installation comes with the various predefined project templates, and we can use one o...

Read More >

What's New In C# 6.0?

Microsoft has released the preview version of Visual Studio 2015 and .NET 4.6 for developers to try ...

Read More >

Creating an RDLC report in Asp.Net

Step 1.  Create a new website and Add DataSet to the WebsiteRight Click on the project, Add new...

Read More >

How to add Overlay in Windows phone 8

Windows Phone is windows mobile operating system from Microsoft.In my project, there was a requireme...

Read More >

Converting UserControl into a dll

User controls are containers into which you can put markup and Web server controls. You can then tre...

Read More >

Share

Comments

ted
Fantastic! How nice! I liked very much How to grow pineapples
4/30/2021 5:36:43 AM | Reply
ted
Fantastic! How nice! I liked very much How to grow pineapples
4/30/2021 5:36:08 AM | Reply
Nice post. For more info about custom soap boxes enjoying a lot while reading this beautiful article.
4/29/2021 4:52:14 PM | Reply
All details you describe in your blog post about soap boxes is very informative for me. Soap boxes provides with suitable price.
4/26/2021 5:12:33 PM | Reply
Soap boxes are uncommon endowments so their packaging ought to likewise be novel and imaginative.Soap boxes are a perfect method.
3/23/2021 7:54:24 PM | Reply
Fascinating blog! Is yor theme custom made or did you downloaad it from somewhere? A theme like yours with a few simple adjustements would really make my blog shine.Please let me know where you got your design. Thank youhttps://flantenac.medium.com/how-to-cite-a-article-in-an-essay-808d592880f0top essay writing websitestop essay writing websites
2/19/2021 11:15:01 PM | Reply
Thank you, I have just been looking for info approximately this suubject for a long timje and yours is the best I have discovered till now.But, what concerning the bottom line? Are you positive concerning the supply?https://susanna4fees.medium.com/online essay writingonline essay writing
2/18/2021 2:15:56 AM | Reply
Way cool! Some very valid points! I appreciate you writing this post and the rest of the site is extremely good. soap boxes
2/6/2021 3:48:05 AM | Reply
Creased mailer boxes, otherwise called ridged delivery boxes, are fundamentally utilized for web based business bundling and membership box bundling. Mailer boxes are layered to give security to items that are transported. These containers can be completely altered with print outwardly and within the crate, giving your clients an Instagram commendable unpacking experience.cereal boxescupcake boxes wholesalewholesale cupcake boxes
1/20/2021 2:32:17 AM | Reply
All details you describe in your blog post about soap boxes wholesale is very informative for me. soap boxes wholesale provides with suitable price.
12/23/2020 6:27:06 PM | Reply
You ought to take part iin a contest foor one of the best sites online.I am going to ighly recommend this blog!https://yescheapessaywriting.comcheap essay writing helpcheap essay writing helphttps://yescheapessaywriting.com
12/7/2020 5:58:43 PM | Reply
Emaar introduced Club Villas at Dubai Hills Estate which offers 3 and 4 bedroom villas, Book with 5%
11/11/2020 5:05:02 PM | Reply
Dubai Real Estate
11/9/2020 11:55:25 AM | Reply
Really very good blog you should definitely check the ethix products soaps best and quality here!
7/31/2020 9:09:22 AM | Reply

Post a Comment

Try DevOpSmartBoard Ultimate complete Azure DevOps End-to end reporting tool

Sign Up

  • Recent
  • Popular
  • Tag
Monthly Archive
Subscribe
Name

Text/HTML
Text/HTML
Contact Us
  • *
  • *