Introduction to CoreWCF for .NET 6

What is CoreWCF?

CoreWCF is an upgrade of Windows Communication Framework (WCF) to .NET Core. CoreWCF is a community-driven open-source project provided by a Microsoft WCF team member. It is used to host various WCF Services to .NET Core. 

As a .NET Foundation project, it allows you to expand Windows Communication Foundation (WCF) on different versions of .NET. Although CoreWCF is not a Microsoft-owned project, Microsoft has declared that it’ll offer product support for CoreWCF. While working with technologies such as gRPC and .NET, ASP.NET WebAPI unit still recommended for whole clean development. With current critical WCF dependencies that have been transferred to.NET6, CoreWCF may be a pleasing alternative.

Features of CoreWCF

CoreWCF may be a set of the practicality from WCF, but represents what we tend to consider square measure the most used options, including:

* Hypertext transfer protocol & NetTCP transports

* Bindings:

– NetHTTPBinding

– BasicHTTPBinding

– NetTCPBinding

– WSHTTPBinding 

– WebHTTPBinding support with OpenAPI feature 

* Security:

– Transport

– NetTcpBinding supports Certificate and Windows authentication

– Transport With Message Credentials

– Hypertext transfer protocol bindings need authentication to be organized in ASP .NET Core         

* WS-Federation support

* Username, Certificate and Windows Authentication square measure supported

* Partial configuration support together with services & endpoints

* New support for injecting HTTPContext, HTTPRequest, and HTTPResponse objects into service implementation ways. This additionally includes supporting the ASP.NET Core FromServicesAttribute additionally to the CoreWCF InjectedAttribute

* WSDL support, together with ServiceDebugBehavior

* Custom Binding support for Configuration

CoreWCF compatibility

CoreWCF is compatible with –

*  .NET Core 3.1

*  .NET Framework 4.6.2+ 

*  .NET 5 & 6

This support for .NET Framework will allow an easy upgradation to .NET Core.

What?s New in .NET 6.0?

Microsoft has disclosed?.NET 6.0?on eighth Nov 2022.? Visual Studio 2022 support .NET 6.0. We previously saw how Microsoft released the Core version of .NET 5 and created the feature differences between ASP.NET and ASP.NET Core.

.NET 6.0 is also a long-run assist release; and they have also mentioned that there will be a support for 3 years. Microsoft recommends Coder to begin to migrate their packages to the prevailing remake, the improve technique fairly straightforward from each .NET Core 3.1 and .NET 5. This remarks the primary time that .NET square measure supported on mac-OS Apple semiconductor. it’ll possible be supported on Windows Arm64.

Let?s get started

The description and commission of data and repair contracts is analogous to WCF. the foremost distinction is at intervals the define of host that is currently grounded on the ASP.NET core, and therefore the operate of however the service is displayed. the next is grounded on. NET 6, however the identical method apply to alternative performances of .NET . 

Step 1 : Create an ASP.NET Core Empty application, this provides the host for the service.

Fig.  Create a Empty application

Step 2 : Add CoreWCF.Primitives & CoreWCF.HTTP from the Package Manager Console

Fig. Required packages to add

https://devblogs.microsoft.com/dotnet/corewcf-v1-released/ – 2-add-references-to-the-corewcf-nuget-packages

Go to Project File and add the following

  • First of unload your project then go to the project file and check for the below code. If the following code is not seen then insert it into the code.

<ItemGroup>

    <PackageReference Include=”CoreWCF.Http” Version=”1.0.2″ />

    <PackageReference Include=”CoreWCF.Primitives” Version=”1.0.2″/> 

</ItemGroup>

Step 3 : Create a Service Contract and Data contract definitions

  • Create a Service contract and Data contract definitions.
  • This square measure outlined the identical like WCF. once modernizing comes, this code will stay mostly unchanged. 
  • Copy the next code to the IEchoDemoService.cs and save the file.

In IEchoProjectService.cs

using System.Diagnostics.CodeAnalysis;

using System.Runtime.Serialization;

using CoreWCF;

namespace CoreWCfProjectServer

{

  [DataContract]

  public class EchoProjectFault

  {

    [AllowNull]

    private string _Message;

    [DataMember]

    [AllowNull]

    public string Message

    {

      get { return _Message; }

      set { _Message = value; }

    }

  }

  [ServiceContract]

  public interface IEchoProjectService

  {

    [OperationContract]

    string Echo(string Message);

    [OperationContract]

    string ComplexEcho(EchoMessage Message);

    [OperationContract]

    [FaultContract(typeof(EchoFault))]

    string FailEcho(string Message);

  }

  [DataContract]

  public class EchoProjectMessage

  {

    [AllowNull]

    [DataMember]

    public string EchoText { get; set; }

  }

}

In EchoProjectService.cs

using CoreWCF;

namespace CoreWCfProjectServer

{

  public class EchoProjectService : IEchoProjectService

  {

    public string Echo(string text)

    {

      System.Console.WriteLine($”Received this message {text} from                                                   

      clientSide!”);

      return text;

    }

    public string ComplexEcho(EchoMessage text)

    {

      System.Console.WriteLine($”Received this message {text.EchoText

 } from

      clientSide!”);

      return text.EchoText;

    }

    public string FailEcho(string text)

        => throw new FaultException<EchoFault>(new EchoFault() { Text =

 “WCF Failure ” }, new FaultReason(” Display the failure reason here 

“));

  }

}

Step 4 : The Service host needs to be told which services to expose via which bindings.

Update the Program.cs with following code and then save the file.

using CoreWCF;

using CoreWCF.Configuration;

using CoreWCF.Description;

using CoreWCfDemoServer;

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel((context, options) =>{

options.AllowSynchronousIO = true;});

// Add WSDL support in the program.cs

builder.Services.AddServiceModelServices().AddServiceModelMetadata();

builder.Services.AddSingleton<IServiceBehavior, UseRequestHeadersForMetadataAddressBehavior>();

var app = builder.Build();

app.UseServiceModel(builder =>{

builder.AddService((serviceOptions) => { })// Add a BasicHttpBinding at a specific endpoint here.AddServiceEndpoint<EchoService, IEchoService>(new BasicHttpBinding(), “/EchoService/basichttp”)// Add a WSHttpBinding with Transport Security for TLS here.AddServiceEndpoint<EchoService, IEchoService>(new WSHttpBinding(SecurityMode.Transport), “/EchoService/WSHttps”);});var serviceMetadataBehavior = app.Services.GetRequiredService();

serviceMetadataBehavior.HttpGetEnabled = true;

app.Run();

Step 5 : Update the appsettings.json

Update the appsetting.json to specify fixed ports for the services to listen on

Add the following code to appsetting.json 

“Urls”: “http://localhost:4000;https://localhost:4001”

Step 6 : Run the project so that the services can be activated

Now to consume the services which we have created, follow these steps:

Step 1 :  Create a Console Application

Step 2 :  Add a Service Reference

Use the “Add Service Reference” command and select “WCF Web Service” as the service sort. 

Fig. Add the service reference

Use http://localhost:4000/EchoProjectService/basichttp as the URL for WSDL discovery.

Step 3 : Now replace the code of the Console app with the following

using ServiceReference1;

var client = new EchoServiceClient(EchoServiceClient.EndpointConfiguration.WSHttpBinding_IEchoProjectService, “https://localhost:4001/EchoService/WSHttps”);

var simplemessageResult = await client.EchoAsync(“Hi “);

Console.WriteLine(simplemessageResult);

var message = new EchoMessage() { Text = “Hi again we are here” };

var messageResult = await client.ComplexEchoAsync(message );

Console.WriteLine(messageResult);

var message = new EchoMessage() { Text = “Hi again we are here” };

var messageResult = await client.ComplexEchoAsync(message );

Console.WriteLine(messageResult);

Conclusion

In this blog, we learnt about CoreWCF in.NET6, as well as its features. We also went through the compatibility requirements, needed namespaces for porting, how to port from WCF to CoreWCF in.NET 6, and how WCF service implementations remain unmodified during the process.

Author Bio: Kapil Panchal ? Digital Marketing Manager
I am working as a Digital Marketing Manager in a reputed .NET development company. Being a technical writing enthusiast and a goal-oriented individual with honed communication skills, I have served in the Information technology, Services, and Product industry. Having a high-energy level, I absolutely love what I do and I?m passionate about being better every day.

Donna

As the editor of the blog, She curate insightful content that sparks curiosity and fosters learning. With a passion for storytelling and a keen eye for detail, she strive to bring diverse perspectives and engaging narratives to readers, ensuring every piece informs, inspires, and enriches.