Step 1: Create a class library to create a WCF contract.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.ServiceModel;
- using System.Runtime.Serialization;
- namespace MyServiceLibrary
- {
- [ServiceContract]
- interface IMyService
- {
- [OperationContract]
- int GetResult(int num1, int num2);
- }
- public class MyService: IMyService
- {
- public int GetResult(int num1, int num2)
- {
- return num1 + num2;
- }
- }
- }
Step 2: Create a console application to host and configure WCF service HTTP and TCP.
Step 3: Open app.config to configure HTTP and TCP binding,
- <system.serviceModel>
- <behaviors>
- <serviceBehaviors>
- <behavior name="b1">
- <serviceMetadata httpGetEnabled="true" />
- </behavior>
- </serviceBehaviors>
- </behaviors>
- <services>
- <service name="MyServiceLibrary.MyService" behaviorConfiguration="b1">
- <endpoint address="" binding="basicHttpBinding" contract="MyServiceLibrary.IMyService"></endpoint>
- <endpoint address="" binding="netTcpBinding" contract="MyServiceLibrary.IMyService"></endpoint>
- <endpoint address="mex1" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
- <endpoint address="mex2" binding="mexTcpBinding" contract="IMetadataExchange"></endpoint>
- <host>
- <baseAddresses>
- <add baseAddress="http://localhost:1111/MyService" />
- <add baseAddress="net.tcp://localhost:1234/MyService" />
- </baseAddresses>
- </host>
- </service>
- </services>
- </system.serviceModel>
Step 4: Open program.cs file to host WCF service. Write code in Main.
- ServiceHost host = new ServiceHost(typeof(MyServiceLibrary.MyService));
- if (host != null)
- {
- host.Open();
- Console.WriteLine("Service Started............");
- Console.ReadLine();
- host.Close();
- }
Step 5: Create client application as ConsoleApplication to consume WCF service.
Step 6: Add a service reference as HTTP or TCP,
- http://localhost:1111/MyService
- net.tcp://localhost:1234/MyService
Step 7: Open program.cs to consume and execute service method. Write code in Main.
- ServiceReference1.MyServiceClient ob1 = new ServiceReference1.MyServiceClient();
- Console.WriteLine(ob1.GetResult(10,20));
Step 8: Execute ConsoleApplication.
Your client application will through an error.
An endpoint configuration section for contract 'ServiceReference1.IMyService' could not be loaded because more than one endpoint configuration for that contract was found. Please indicate the preferred endpoint configuration section by name.
Solution
- Open web.config file from client application and copy binding name under binding section and add this binding name as a string parameter for ServiceReferences. Like this:
- ServiceReference1.MyServiceClient ob1 = new ServiceReference1.MyServiceClient("BasicHttpBinding_IMyService");
- Open web.config file from client application and remove one of the bindings.
Step 9: Test your client application.