Sunday, 24 December 2017

Creating WCF Service with wsHttpBinding and webHttpBinding together

In this tutorial, I am going to explain you how to create .NET WCF Service with wsHttpBinding and webHttpBinding together in single WCF application. Below topics will be covered in this tutorial.

  • Creating new WCF Service application project
  • Creating simple calculator service
  • Creating complex / CompositeType calculator service
  • Configuring service with wsHttpBinding and webHttpBinding
  • Calling simple and complex service using .NET application by creating Proxy Class (wsHttpBinding)
  • Calling simple and complex service using REST client like POSTMAN (webHttpBinding)
  • Calling simple and complex service using jQuery (webHttpBinding)

Creating new WCF Service application project

I will be using visual studio 2013 and .NET framework 4.5.
Go to FileNewProject. A new window will be open as shown below.
Now go to Visual C# and search for WCF Service Application and give project name and click on OK .

Creating WCF Service application

Now a wcf service will be created with default template as shown below.

WCF Service folder structure

1) Now rename IService1.cs to ICalc.cs and Service1.svc to Calc.svc.
2) Now right click on Calc.svc, go to View Markup and change service from Service="WcfService1.Service1" to Service="WcfService1.Calc".

Creating simple and Complex calculator service

Now open ICalc.cs file, delete all the default code generated and replace its with new code as shown below. Here we have declared two method Calculator1 and Calculator2 inside inteface, both are decorated with POST verb and returns Json data. Calculator1 method accepts two integer parameter where as Calculator2 method accepts a complex class objects and both returns addition of two numbers.

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

namespace WcfService1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface ICalc
    {
        //simple calculator service
        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        string Calculator1(int FirstNumber, int SecondNumber);

        //complex / CompositeType calculator service
        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        Calculator2Output Calculator2(Calculator2Input Calc2Input); // input and output is of some CompositeType type
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class Calculator2Input
    {
        [DataMember]
        public int FirstNumber { get; set; }

        [DataMember]
        public int SecondNumber { get; set; }
    }

    [DataContract]
    public class Calculator2Output
    {
        [DataMember]
        public string AdditionResult { get; set; }
    }
}

Now open Calc.svc.cs file, delete all the default code generated and replace its with new code as shown below. Here provide the implementation for both the methods.

Calc.svc.cs Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Calc : ICalc
    {
        public string Calculator1(int FirstNumber, int SecondNumber)
        {
            return "Addition is : " + Convert.ToString(FirstNumber + SecondNumber);
        }

        public Calculator2Output Calculator2(Calculator2Input Calc2Input)
        {
            Calculator2Output obj = new Calculator2Output();

            obj.AdditionResult = "Addition is : " + (Calc2Input.FirstNumber + Calc2Input.SecondNumber).ToString();

            return obj;
        }
    }
}

Configuring service with wsHttpBinding and webHttpBinding

Now open web.config file of wcf application. Replace <system.serviceModel> code with code provided below. Here ws address is for wsHttpBinding and web is for webHttpBinding.

<?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>
          -->
  <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
  <!--
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          -->
  <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
  <!--
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>   
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>-->
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="Default" name="WcfService1.Calc">
        <endpoint address="web" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="WcfService1.ICalc" />
        <endpoint address="ws" binding="wsHttpBinding" bindingConfiguration="wsBehavior" contract="WcfService1.ICalc" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp />
          <!--<enableWebScript/>-->
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="Default">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="wsBehavior">
          <security mode="None" >
            <transport clientCredentialType="None"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

Now run your application and you should see output shown below.

Successfully executing WCF Service application

Access WCF service using .NET application by creating Proxy Class (wsHttpBinding)

Now create an ASP.NET Webform application or Console application or MVC application where you want to access or consume WCF Service. Let's create a console application.

Create a Proxy Class

We have created a console application. Now Right click on Refrences folder of console application and Click on Add Service Reference as below.

Adding service reference to .net application

Now a new window will open as shown below. In address textbox, put URL of your WCF Service and click on Go button. Make sure your WCF Service application is running, in our case it is running on localhost. Give namespace name as MyServiceReference and finally click on OK.

Creating proxy class of wcf service application

Now visual studio will generate proxy class to communicate to WCF Service. Now open your app.config file of console application or web.config file in case of webform application, here you can see, console application will be using wsHttpBinding binding by-default.

App.config code generated
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_ICalc">
          <security mode="None" />
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:30368/Calc.svc/ws" binding="wsHttpBinding"
          bindingConfiguration="WSHttpBinding_ICalc" contract="MyServiceReference.ICalc"
          name="WSHttpBinding_ICalc" />
    </client>
  </system.serviceModel>

</configuration>

Below is code to call wcf service in .net application using proxy class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Simple
            MyServiceReference.CalcClient obj = new MyServiceReference.CalcClient();
            string Calculator1Result = obj.Calculator1(10, 20);

            // Complex
            MyServiceReference.Calculator2Input input = new MyServiceReference.Calculator2Input();
            input.FirstNumber = 10;
            input.SecondNumber = 20;

            MyServiceReference.Calculator2Output output = obj.Calculator2(input);
            string Result = output.AdditionResult;
        }
    }
}
Access wcf service using proxy class client

Access WCF service using REST Client (POSTMAN)

Now we will access wcf service by using REST client like POSTMAN or you can use fiddler tool. You can install POSTMAN extension using google chrome browser.

Using Json DataType for Calculator1 method

1) Now open the POSTMAN, Select POST from dropdown.
2) Enter URL of WCF Service and append /web/method_name to end of the URL as we have given web for webHttpBinding and ws for wsHttpBinding in web.config of wcf service.
3) Go to Body tab, select raw radio button and select JSON(application/json) from dropdown.
4) Now put json data in body and click on SEND button as shown below. Response in json format can be seen second tab.

Access wcf rest service using rest client with json data

Using Json DataType for Calculator2 method

Repeat same process for Calculator2 method. You can see the output below.

Access complex wcf rest service using rest client with json data

Using XML DataType for Calculator1 method

Repeat same process as we did for json datatype. We need to select JSON(application/xml) from dropdown.
To get xml input data format, go to WCF application, open Calc.svc.cs file and run application. Now WCF test client will get open. Click on Calculator1 method and go to XML tab copy XML code from body section as highlighted below.

Execute wcf service using WCF Test client

Now go to POSTMAN and in body section paste the copied xml code and click on send button and response can be seen as below.

Access wcf rest service using rest client with xml data

Using XML DataType for Calculator2 method

Repeat same process for Calculator2 method. Here XML generated using WCF test client is different from Calculator1 method as shown below.

Access complex wcf rest service using rest client with xml data

Access WCF service using jQuery Ajax

Now we will access WCF Service using jQuery ajax method using webHttpBinding. But before access let's make some changes in WCF Service application. Go to WCF service application, add global.asax file if it not already added. Overwrite the Application_BeginRequest with below code.

Global.asax file Code
protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}

Access Calculator1 method using jQuery Ajax method

Create a HTML file and write below jquery code to access wcf service. Below html file contails two textboxes, one button and a label to display addtition on two numbers.

HTML and jQuery Code for Calculator1 method
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#btnCalculate').click(function () {
                var txtFirstNumber = $('#txtFirstNumber').val();
                var txtSecondNumber = $('#txtSecondNumber').val();
                $.ajax({
                    url: 'http://localhost:30368/Calc.svc/web/Calculator1',
                    method: 'POST',
                    contentType: "application/json;charset=utf-8",
                    data: JSON.stringify({ 'FirstNumber': txtFirstNumber, 'SecondNumber': txtSecondNumber }),
                    dataType: 'json',
                    success: function (response) {
                        $('#lblResult').text(response.Calculator1Result);
                    },
                    error: function (err) {
                        alert(err);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <table>
        <tr><td>First Number</td><td><input type="text" id="txtFirstNumber" /></td></tr>
        <tr><td>Second Number</td><td><input type="text" id="txtSecondNumber" /></td></tr>
        <tr>
            <td><input type="button" id="btnCalculate" value="Add here to add" /></td>
            <td><label id="lblResult" style="color:green;"></label> </td>
        </tr>
    </table>
</body>
</html>

Output can be seen as below.

Access wcf service using jquery ajax with webhttpbinding
jQuery Code for Calculator2 method
<script>
    $(document).ready(function () {
        $('#btnCalculate').click(function () {
            var data = {};
            data.FirstNumber = $('#txtFirstNumber').val();
            data.SecondNumber = $('#txtSecondNumber').val();

            $.ajax({
                url: 'http://localhost:30368/Calc.svc/web/Calculator2',
                method: 'POST',
                contentType: "application/json;charset=utf-8",
                data: "{\"Calc2Input\":" + JSON.stringify(data) + "}",
                dataType: 'json',
                success: function (response) {
                    $('#lblResult').text(response.Calculator2Result.AdditionResult);
                },
                error: function (err) {
                    alert(err);
                }
            });
        });
    });
</script>

Data should be in below format for Calculator 2 method.
{"Calc2Input":{"FirstNumber":"10","SecondNumber":"20"}}

Share:

2 comments:

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

Ads By Chitika