You have a WCF service that still runs the business, maybe a SOAP endpoint from an older system or a partner, and a new .NET app has to call it. The old app.config and Add Service Reference habits from .NET Framework are gone, and the tutorials you find still show .NET Core 2.1 and Visual Studio 2017.
You can consume a WCF service in C# on current .NET in two ways: generate a typed client with dotnet-svcutil (the engine behind the Visual Studio Connected Services WCF Web Service Reference Provider), or build the channel yourself with ChannelFactory. Both use the open source WCF client libraries published as the System.ServiceModel.* NuGet packages (version 10.1.0 here).
The code below was compiled on .NET 10 and run against a local CoreWCF service over both BasicHttpBinding and NetTcpBinding. The animation shows the one habit that prevents most production surprises: closing a channel differently when it is faulted.

- Which approach should you choose?
- Prerequisites
- Step 1: Get a WCF service to call
- Step 2: Generate the client with dotnet-svcutil
- Step 3: Call the generated client
- Option B: Use ChannelFactory without generated code
- Bindings, endpoints and timeouts
- Close and Abort: handle faulted channels
- Authentication basics
- What the output looks like
- Common problems and fixes
- CoreWCF, gRPC or REST: what next?
- Frequently asked questions
- Summary
Which approach should you choose?
- Generated client (dotnet-svcutil or Connected Services): reads the WSDL and writes typed classes for you. Best when you have a WSDL and many operations or data contracts. Re-run it when the service changes.
- ChannelFactory with your own contract: you write a small interface decorated with
[ServiceContract]and create the channel in code. Best when you share a contract assembly with the service, or want no generated code and full control of the binding. - HttpClient with a hand-built SOAP envelope: only for one or two simple calls. It works, but you lose WS-* features, faults and serialization.
This post is for the first two. Both give the same result at runtime, because the generated client is a wrapper around ClientBase<T>, which uses ChannelFactory internally.
Prerequisites
- A .NET 8, 9 or 10 project. The WCF client packages work in console apps, ASP.NET Core and worker services.
- The service URL or WSDL, for example
http://localhost:5080/OrderService.svc?wsdl. - The
dotnet-svcutilglobal tool (it needs a .NET runtime it supports; the 8.0.0 tool ran here withDOTNET_ROLL_FORWARD=Majoron a machine that only had .NET 10).
dotnet add package System.ServiceModel.Http
dotnet add package System.ServiceModel.NetTcp
dotnet add package System.ServiceModel.Primitives
dotnet tool install --global dotnet-svcutil
Step 1: Get a WCF service to call
If you do not have a service handy, host one with CoreWCF, the community port of the server side of WCF for .NET. Create an empty web project and add CoreWCF.Http, CoreWCF.NetTcp and CoreWCF.Primitives (1.9.2 here). This host exposes one contract on both a BasicHttp and a NetTcp endpoint and publishes the WSDL.
using CoreWCF;
using CoreWCF.Configuration;
using CoreWCF.Description;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(o =>
{
o.ListenLocalhost(5080);
});
builder.WebHost.UseNetTcp(5808);
builder.Services.AddServiceModelServices().AddServiceModelMetadata();
builder.Services.AddSingleton<IServiceBehavior, UseRequestHeadersForMetadataAddressBehavior>();
var app = builder.Build();
app.UseServiceModel(sb =>
{
sb.AddService<OrderService>();
sb.AddServiceEndpoint<OrderService, IOrderService>(new BasicHttpBinding(), "/OrderService.svc");
sb.AddServiceEndpoint<OrderService, IOrderService>(new NetTcpBinding(SecurityMode.None), "net.tcp://localhost:5808/OrderService");
var smb = app.Services.GetRequiredService<ServiceMetadataBehavior>();
smb.HttpGetEnabled = true;
});
app.Run();
[ServiceContract(Namespace = "http://thecodebuzz.com/orders")]
public interface IOrderService
{
[OperationContract] string GetStatus(int orderId);
[OperationContract] [FaultContract(typeof(string))] decimal GetTotal(int orderId);
[OperationContract] Task<string> SlowAsync(int ms);
}
public class OrderService : IOrderService
{
public string GetStatus(int orderId) => $"Order {orderId} shipped";
public decimal GetTotal(int orderId) =>
orderId > 0 ? 49.90m * orderId : throw new FaultException<string>("Unknown order", "Order id must be positive");
public async Task<string> SlowAsync(int ms) { await Task.Delay(ms); return "done"; }
}
Run it with dotnet run and open http://localhost:5080/OrderService.svc?wsdl to confirm the WSDL loads. Against your real service you skip this step.
Step 2: Generate the client with dotnet-svcutil
Run the tool in your client project. -n sets the namespace, -d the output folder and -o the file name.
dotnet-svcutil "http://localhost:5080/OrderService.svc?wsdl" -n "*,OrderClient" -d Proxy -o OrderServiceReference.cs
It writes Proxy/OrderServiceReference.cs and dotnet-svcutil.params.json (the saved options, so you can regenerate with dotnet-svcutil -u). Treat the file as generated code and do not edit it. Inside you will find the contract interface, IOrderServiceChannel, the OrderServiceClient class and an EndpointConfiguration enum.
In Visual Studio the same thing is Connected Services > Add > WCF Web Service Reference (the dotnet-svcutil guide documents the tool and its options). If the entry is missing, install the WCF component through the Visual Studio Installer. The Visual Studio UI itself was not run for this post; the command line is the same generator.
Two things to know about the tool. It may add older System.ServiceModel.Duplex, Security and Federation 4.10.* references to your project file; remove the ones you do not use. It also generates only the endpoints and bindings listed in the WSDL, so a NetTcp endpoint that is not in the WSDL has to be created in code (see below).
Step 3: Call the generated client
using System.ServiceModel;
using OrderClient;
var generated = new OrderServiceClient(
OrderServiceClient.EndpointConfiguration.BasicHttpBinding_IOrderService,
"http://localhost:5080/OrderService.svc");
try
{
Console.WriteLine(await generated.GetStatusAsync(42));
await generated.CloseAsync();
}
catch
{
generated.Abort(); // never Close() a faulted client
throw;
}
Passing the address overrides the one baked into the generated file, which is what you want when the URL differs per environment. Read it from configuration, for example IOptions, rather than hard coding it. If you register the client for dependency injection, create it per operation or per request and avoid a long lived singleton, because one fault leaves it unusable.
Option B: Use ChannelFactory without generated code
Without generated code, declare the contract yourself. The Name, Namespace and Action values must match the WSDL, so copy them from the generated file or from the service. Adding IClientChannel to the channel interface gives you State, Close and Abort without casting.
[ServiceContract(Name = "IOrderService", Namespace = "http://thecodebuzz.com/orders")]
public interface IOrderContract
{
[OperationContract(Action = "http://thecodebuzz.com/orders/IOrderService/GetStatus", ReplyAction = "http://thecodebuzz.com/orders/IOrderService/GetStatusResponse")]
Task<string> GetStatusAsync(int orderId);
[OperationContract(Action = "http://thecodebuzz.com/orders/IOrderService/GetTotal", ReplyAction = "http://thecodebuzz.com/orders/IOrderService/GetTotalResponse")]
[FaultContract(typeof(string), Action = "http://thecodebuzz.com/orders/IOrderService/GetTotalStringFault", Name = "string", Namespace = "http://schemas.microsoft.com/2003/10/Serialization/")]
Task<decimal> GetTotalAsync(int orderId);
[OperationContract(Action = "http://thecodebuzz.com/orders/IOrderService/Slow", ReplyAction = "http://thecodebuzz.com/orders/IOrderService/SlowResponse")]
Task<string> SlowAsync(int ms);
}
public interface IOrderChannel : IOrderContract, IClientChannel { }
Then call it through a small helper that always releases the channel and the factory. It is the full pattern for production code. For a hot path, create the ChannelFactory once and reuse it, because building one is the expensive part; channels are cheap to create and should not be shared after a fault.
static async Task<T> CallAsync<T>(Binding binding, EndpointAddress address, Func<IOrderChannel, Task<T>> call)
{
var factory = new ChannelFactory<IOrderChannel>(binding, address);
var channel = factory.CreateChannel();
try
{
return await call(channel);
}
finally
{
CloseSafely((ICommunicationObject)channel);
CloseSafely(factory);
}
}
Bindings, endpoints and timeouts
The binding must match what the service endpoint exposes, so ask the service owner or read the WSDL. These are the two you will meet most.
- BasicHttpBinding: SOAP 1.1 over HTTP or HTTPS. Works with ASMX and most WCF services. Use
BasicHttpSecurityMode.Transportfor HTTPS. - NetTcpBinding: binary over TCP, WCF to WCF only, usually inside one network. Port and address are separate from HTTP, as in
net.tcp://host:5808/OrderService. - WSHttpBinding and NetHttpBinding exist in the packages too. Named pipes, MSMQ and the Windows only features of full WCF are not available on the client.
var http = new BasicHttpBinding
{
OpenTimeout = TimeSpan.FromSeconds(5),
SendTimeout = TimeSpan.FromSeconds(2), // time to send the request and get the reply
ReceiveTimeout = TimeSpan.FromSeconds(10),
};
var httpAddress = new EndpointAddress("http://localhost:5080/OrderService.svc");
var tcp = new NetTcpBinding(SecurityMode.None); // SecurityMode.None only for a trusted local test
var tcpAddress = new EndpointAddress("net.tcp://localhost:5808/OrderService");
Console.WriteLine(await CallAsync(http, httpAddress, c => c.GetStatusAsync(7)));
Console.WriteLine(await CallAsync(tcp, tcpAddress, c => c.GetStatusAsync(8)));
Timeouts are the settings people forget. The defaults are one minute for open, close and send (ten minutes for receive), so a hung service can hold a request for a minute or more. Set SendTimeout to the longest call you accept. For large replies also raise MaxReceivedMessageSize (the generated bindings set it to int.MaxValue; choose a sane limit instead).
Close and Abort: handle faulted channels
A WCF channel can end up in the Faulted state after a timeout, a connection error or an unhandled service exception. Calling Close() on a faulted channel throws, and a using block makes it worse: Dispose calls Close, so the second exception hides the real one. This happened while testing this post, with using (var factory = ...) replacing the actual error with CommunicationObjectFaultedException. Use this helper in a finally block instead.
static void CloseSafely(ICommunicationObject c)
{
try
{
if (c.State == CommunicationState.Faulted) c.Abort(); else c.Close();
}
catch (CommunicationException) { c.Abort(); }
catch (TimeoutException) { c.Abort(); }
catch { c.Abort(); throw; }
}
The rule: Close() when healthy, Abort() when faulted or when Close() throws. A declared FaultException<T> was caught as shown below, and the helper closed the channel afterwards. Timeouts and transport errors fault the channel, and fault behavior differs by binding, so never reuse a channel after an exception; create a new one.
try { await CallAsync(http, httpAddress, c => c.GetTotalAsync(-1)); }
catch (FaultException<string> ex) { Console.WriteLine("fault detail: " + ex.Detail); }
catch (TimeoutException) { /* retry or give up; the helper already aborted */ }
catch (CommunicationException) { /* endpoint down, TLS or binding mismatch */ }
Order matters: FaultException and TimeoutException before the general CommunicationException. If you retry, add a backoff policy; Polly resilience for HTTP calls shows the idea and the same policies apply around a WCF call.
Authentication basics
Set credentials on the factory (or on client.ClientCredentials for a generated client) before the first call. Send secrets only over HTTPS, and read them from configuration or a secret store.
var secure = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
secure.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
var factory = new ChannelFactory<IOrderChannel>(secure,
new EndpointAddress("https://example.invalid/OrderService.svc"));
factory.Credentials.UserName.UserName = "svc-user";
factory.Credentials.UserName.Password = Environment.GetEnvironmentVariable("WCF_PASSWORD") ?? "";
// For certificate auth: factory.Credentials.ClientCertificate.SetCertificate(...)
Other common choices are HttpClientCredentialType.Windows (Kerberos or NTLM, set factory.Credentials.Windows), Certificate and message level UserName security with BasicHttpSecurityMode.TransportWithMessageCredential. This block only compiles here: it was not run against a secured service.
What the output looks like
The full test program (generated client, both bindings, a fault, a timeout and an unreachable port) printed:
Common problems and fixes
- CommunicationObjectFaultedException on Close or Dispose: you closed a faulted channel. Use
CloseSafelyand do not wrap the factory inusing. - ProtocolException: does not support .Net Framing: you used NetTcpBinding against an HTTP port, or the service does not listen for net.tcp at that port. Check the address scheme and port.
- TimeoutException: the service was slower than
SendTimeout, or it did not answer at all. Raise the timeout only if the call is legitimately slow. - CommunicationException: Connection refused: wrong host or port, or the service is down. On .NET this surfaced as a plain
CommunicationException, notEndpointNotFoundExceptionas in .NET Framework. - ActionNotSupportedException or empty replies: the
Namespace,NameorActionin your own contract differs from the WSDL. Compare with the generated file. - Certificate or TLS errors: the service certificate is not trusted on the client machine. Fix the trust chain; do not disable validation in production.
- Generated code does not compile after regeneration: delete old generated files and the extra 4.10.* package references, then run
dotnet-svcutil -uagain.
CoreWCF, gRPC or REST: what next?
Consuming WCF from .NET is fully supported, but WCF server hosting is not part of modern .NET. If you must keep a WCF service running, CoreWCF lets you host it on ASP.NET Core and keeps existing clients working, which is how the test service above was built. For new work consider these paths:
- gRPC for service to service calls inside your network. Microsoft publishes a gRPC for WCF developers guide that maps WCF concepts to gRPC.
- REST over HTTP for public or browser facing APIs. You can even expose an existing contract that way; see enable existing WCF services as a REST API for the HTTP route.
- Keep the SOAP client when the service belongs to someone else. Wrap it behind your own interface so the rest of the app never sees WCF types, and replacing it later is a small change.
Related posts: ChannelFactory in more detail and the dotnet-svcutil global tool.
Frequently asked questions
How do I consume a WCF service in .NET 8, 9 or 10?
Install System.ServiceModel.Http (and NetTcp if needed), generate a client with dotnet-svcutil or Visual Studio Connected Services, then call the generated client or a ChannelFactory and always close the channel with Close or Abort.
Is WCF supported in .NET Core and .NET 10?
Only the client side. The System.ServiceModel packages let .NET call WCF services, but hosting a WCF service needs CoreWCF or the .NET Framework.
Should I use ChannelFactory or the generated client?
Use the generated client when you have a WSDL and want typed contracts quickly. Use ChannelFactory when you share a contract assembly or want full control of bindings and no generated code.
Summary
To consume a WCF service on current .NET, add the System.ServiceModel packages, generate a client with dotnet-svcutil (or write a contract for ChannelFactory), pick the binding that matches the endpoint, set timeouts, and release every channel with Close or Abort depending on its state. Tested here: the generated client, ChannelFactory over BasicHttpBinding and NetTcpBinding, a typed fault, a timeout and an unreachable endpoint, all against a local CoreWCF service on .NET 10. Only compiled, not run: the credential setup, and the Visual Studio Connected Services dialog. Not tested: message security, certificates, WSHttpBinding, duplex contracts, .NET 8 and 9, and a real legacy IIS service.
Found this useful?
Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.
