IC Improve Code Recipes

Recipe 13.4 · C#

Calling Legacy SOAP and WCF Services

Problem

The rates service, the policy-admin system or the state reporting endpoint speaks SOAP, and it is not going to change. Your new code runs on .NET 8, where Add Service Reference and the System.ServiceModel you knew from .NET Framework are not built in.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: Dispose throws on a faulted channel and hides the error
using (var client = new RateServiceClient())
{
    return client.GetRate("USD", "EUR");
}

The generated WCF client implements IDisposable, and its Dispose calls Close. If the call faulted, the channel is in the Faulted state, Close throws a CommunicationObjectFaultedException, and that exception replaces the original one. Your log says "the communication object cannot be used because it is in the Faulted state" and the real cause, perhaps a SOAP fault saying the currency code is invalid, is lost. On .NET Framework the endpoint, binding and timeouts also lived in a long <system.serviceModel> section in web.config.

The improved recipe

The WCF client libraries are available for modern .NET as NuGet packages: System.ServiceModel.Http for HTTP bindings and System.ServiceModel.Primitives for the core types. Generate a proxy with dotnet-svcutil, or for a small service write the contract by hand, and manage the channel with a helper that closes on success and aborts on failure.

To generate a client from the service's WSDL:

PowerShell
dotnet tool install --global dotnet-svcutil
dotnet-svcutil https://legacy.example.com/RateService.svc?wsdl `
    --namespace "*,ImproveCode.Legacy.Rates" `
    --outputDir Connected/RateService

For a service with a handful of operations, a hand-written contract is shorter and easier to read than the generated file:

C#
using System.ServiceModel;
using System.Threading.Tasks;

namespace ImproveCode.Legacy;

[ServiceContract(Namespace = "http://example.com/rates/2006")]
public interface IRateService
{
    [OperationContract]
    Task<decimal> GetRateAsync(string fromCurrency, string toCurrency);
}
C#
using System;
using System.ServiceModel;
using System.Threading.Tasks;

namespace ImproveCode.Legacy;

public static class ChannelFactoryExtensions
{
    /// <summary>Opens a channel, runs one call, closes it on
    /// success and aborts it on failure.</summary>
    public static async Task<TResult> CallAsync<TChannel, TResult>(
        this ChannelFactory<TChannel> factory,
        Func<TChannel, Task<TResult>> call)
    {
        TChannel channel = factory.CreateChannel();
        var communication = (ICommunicationObject)channel!;
        bool closed = false;
        try
        {
            TResult result = await call(channel);
            communication.Close();
            closed = true;
            return result;
        }
        finally
        {
            if (!closed)
            {
                communication.Abort();
            }
        }
    }
}
C#
using System;
using System.ServiceModel;
using System.Threading;
using System.Threading.Tasks;

namespace ImproveCode.Legacy;

public sealed class RateServiceGateway : IDisposable
{
    private readonly ChannelFactory<IRateService> _factory;

    public RateServiceGateway(
        Uri endpoint, string userName, string password)
    {
        var binding = new BasicHttpsBinding(
            BasicHttpsSecurityMode.Transport)
        {
            MaxReceivedMessageSize = 4 * 1024 * 1024,
            OpenTimeout = TimeSpan.FromSeconds(10),
            SendTimeout = TimeSpan.FromSeconds(30),
            ReceiveTimeout = TimeSpan.FromSeconds(30),
        };
        binding.Security.Transport.ClientCredentialType =
            HttpClientCredentialType.Basic;

        _factory = new ChannelFactory<IRateService>(
            binding, new EndpointAddress(endpoint));
        _factory.Credentials.UserName.UserName = userName;
        _factory.Credentials.UserName.Password = password;
    }

    public Task<decimal> GetRateAsync(
        string from, string to, CancellationToken ct = default) =>
        _factory.CallAsync(channel =>
            channel.GetRateAsync(from, to).WaitAsync(ct));

    public void Dispose()
    {
        if (_factory.State == CommunicationState.Faulted)
        {
            _factory.Abort();
        }
        else
        {
            _factory.Close();
        }
    }
}

Register the gateway as a singleton, with the endpoint and credentials from configuration:

C#
builder.Services.AddSingleton(sp => new RateServiceGateway(
    new Uri(builder.Configuration["Rates:Endpoint"]!),
    builder.Configuration["Rates:UserName"]!,
    builder.Configuration["Rates:Password"]!));

How it works

dotnet-svcutil is the modern replacement for Add Service Reference. It reads the WSDL, writes a C# file with the data contracts, a service contract interface and a client class, and adds the System.ServiceModel.* package references. The generated operations are asynchronous by default. The generated client is a partial class with a ConfigureEndpoint partial method, so you can set timeouts and credentials in your own file and regenerate without losing them.

The hand-written contract shows how little is really needed. The Namespace on [ServiceContract] must match the service's target namespace from the WSDL, and the operation and parameter names must match the message parts. Get either wrong and the server replies with a fault about an unrecognized action, or the parameters arrive empty.

ChannelFactory<T> is expensive to create and thread-safe once opened, so the gateway builds one and keeps it. Channels are cheap. CallAsync creates one per call, runs the operation, and then either closes it cleanly or aborts it. Abort never throws, so the original exception, whether a FaultException, a TimeoutException or a CommunicationException, is the one that reaches your log.

The binding replaces the old web.config section. Every value that used to live in XML is now a property you can see, review and bind from configuration. MaxReceivedMessageSize matters more than any other: the default is 64 KB, and the first large response fails with a quota error.

Variations and pitfalls

  • Match the package version to your runtime. The System.ServiceModel.* packages version along with .NET. Version 8.1.2 works on .NET 8 and .NET 9; newer major versions may require a newer target framework.
  • What the client packages support. HTTP and HTTPS bindings, NetTcpBinding (with the System.ServiceModel.NetTcp package), transport security and basic, Windows or certificate credentials. Full message-level WSHttpBinding security and some WS-* features are limited or missing. Check before you promise a migration date.
  • Cancellation. WCF operations don't take a CancellationToken. WaitAsync(ct) stops your code from waiting, but the call keeps running until SendTimeout. Keep that timeout realistic.
  • Hosting a WCF service on modern .NET. The client packages only call services. To host one, use CoreWCF, the community port supported by Microsoft, which lets existing SOAP clients keep working while the server moves to ASP.NET Core.
  • Tiny services. For one operation with a simple envelope, posting the SOAP XML with HttpClient and reading the result with LINQ to XML (Chapter 12) is a valid choice. It also gets you the factory and the resilience handler.
  • Secrets. The service password belongs in a secret store, not in appsettings.json. See Chapter 6.

On .NET Framework

The CallAsync helper works on .NET Framework with the built-in System.ServiceModel. It is worth adding to old projects on its own, because it fixes the hidden-exception problem without touching the generated proxies.