Search This Blog

Thursday, 1 August 2024

CoreWCF - Service and client creation step by step

 CoreWcf is used with .Net Core versions. Let us see how a simple WCF service and its client can be created using BasicHttpBinding

Creating the Server Side Setup - Core WCF Service Application

Step 1: Create a new core Wcf application 

> dotnet new web -n CoreWcfServer

> cd CoreWcfServer

At this point a basic boiler-plate code with a service contract and data contract is generated in the project as shown in the screenshots

Data Contract

Service Contract


Step 2: Make sure the following packages are installed. If not install them using the given command.

> dotnet add package CoreWCF.Http

> dotnet add package CoreWCF.Primitives


Step 3: In Program.cs make sure you add the highlighted lines in the screenshot. 

            Make a note of the Binding used at line: 12 - BasicHttpBinding(BasicHttpSecurityMode.Transport)


Step 4: Run the service project. Browse to: https://localhost:7104/MetaData 

This completes the configuration for a Core Wcf Service Application project


Creating a Console Client

The bindings exposed by the core WCF app can only be used by the client application. In this case, BasicHttpBinding can be the only binding that can be used

Step 1: Create a console app

> dotnet new console -n WcfConsoleClient

> cd WcfConsoleClient

Step 2: Make sure the same nuget packages are installed for this project, as installed for the WCF app.

             The server and client apps should contain the same ServiceModel packages

> dotnet add package System.ServiceModel.Primitives

> dotnet add package System.ServiceModel.Http

Step 3: Auto-generate the service reference to the Wcf Service app. For this we will require to install the tool dotnet-svcutil. This will help generate the service reference (proxy class), the metadata using which the calls to the service can be made

> dotnet tool install --global dotnet-svcutil

> dotnet-svcutil https://localhost:7104/MetaData?wsdl

** Some antiviruses can block the bootstrapperutil module in dotnet-svcutil, as it is not a signed module. Hence, use the following option

> dotnet-svcutil https://localhost:7104/MetaData?wsdl --noTypeReuse

 

Step 4: Add the following code in Program.cs



  

using ServiceReference;

using System.ServiceModel;


var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);

var endpoint = new EndpointAddress("https://localhost:7104/Service.svc");


var channelFactory = new ChannelFactory<IService>(binding, endpoint);

var client = channelFactory.CreateChannel();


CompositeType result = await client.GetDataUsingDataContractAsync(new CompositeType() { BoolValue=true, StringValue="A new string"});

Console.WriteLine($"Result from service: {result.StringValue} - {result.BoolValue}");


((IClientChannel)client).Close();

channelFactory.Close();

Console.ReadKey(); 


Step 5: Run your Wcf Service App first, then run the WcfConsoleClient