Consume a WCF Service in C# .NET (Connected Services)

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.

Animation of a WCF client channel: a healthy channel is closed with Close, a faulted channel after a timeout must be released with Abort
Check the channel state: Close when healthy, Abort when faulted.

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-svcutil global tool (it needs a .NET runtime it supports; the 8.0.0 tool ran here with DOTNET_ROLL_FORWARD=Major on 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.Transport for 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:

generated: Order 42 shipped factory http: Order 7 shipped factory tcp: Order 8 shipped fault detail: Unknown order timeout: TimeoutException unreachable: CommunicationException done

Common problems and fixes

  • CommunicationObjectFaultedException on Close or Dispose: you closed a faulted channel. Use CloseSafely and do not wrap the factory in using.
  • 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, not EndpointNotFoundException as in .NET Framework.
  • ActionNotSupportedException or empty replies: the Namespace, Name or Action in 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 -u again.

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.

22 thoughts on “Consume a WCF Service in C# .NET (Connected Services)”

  1. I have implemented the same way as you discussed by using Service Reference. I have instantiated the proxy client in the controller as well. I am getting an error “unable to resolve service for type ‘ServiceReference1.DocumentServiceConverterClient’while attempting to activate API.controllers.conversionController”. It would be really great if you can please provide any resolution for this!!

    1. Hello Riya- If you are not using dependency injection then try to instantiate the DocumentServiceConverterClient correctly,You can use Constructor of controller to initialize instance or use it the way explain the the POC sample in the article.
      If using dependency injection, then try using IOC correctly like example if possible “services.AddScoped()”;

      Hope this helps !

  2. Hi
    Very use full article. Am facing HTTP Error 500.30 – ANCM In-Process Start Failure error post integrating the connected service.

    Without service when i deploy the things work but when deployed with connected service i get the HTTP Error 500.30 – ANCM In-Process Start Failure error.

    Pls can you on the same

    1. Hey Vinay- Thanks for your query. May I know target service Hosting model is Inprocess or out process? Please see switching it has any effect. Please look into the Windows log for more details on the error.

  3. Creating instance of service for every call may cause issue in big application. Do you have any solution for that.

    1. Hey Shekhar- Agree. You could try creating a singleton instance of the proxy class and use it for all other API where it is needed.
      Let me know if that helps!. Thanks.

  4. Hi- Great article. I need to connect to few legacy .asmx services. May i know if above approaches will work for it ? I have not tried yet though.

  5. Thanks for this article.

    I want to consume a WCF service with custom bindings, but all of the above methods fail.This is the error message I get with the 3rd method:

    {System.InvalidOperationException: Contract requires Session, but Binding ‘CustomBinding’ doesn’t support it or isn’t configured properly to support it.

    Any suggestion to get this working is appreciated.

    1. Hi Isha,

      Thanks for your comments. Based on the details you shared, you can try a few options.
      But before you could try anything you should verify WSDL or contract definition for understanding the contract details. Please try using the same configuration as required for vendor Service.
      1. Try to use WsHttpBinding instead of BasicHttpBinding
      2. WsHttpBinding supports session details.
      3. As Andrade mentioned above, you can try to consider using .NET Standard project to use WsHttpBinding along with .Net core client.
      4. WsHttpBinding is not supported in .NET Core but as suggested above .NET Standard project can help.

      Let me know for any queries or questions.

  6. Thanks for this article. It’s rather clarifying, thanks for the insightful explanation. But I still have an issue!

    Here, at my company, we have a couple of awfully ancient ASMX (framework 2) web services that aren’t somehow compatible with svcutil tool. We didn’t find a way to create a client for those using your mentioned tools (we don’t know precisely why).

    We managed to find a workaround using an “extra” .NET Standard Project, but it doesn’t seem right. Any tips about it?

    1. Hi Andrade, Thanks for your feedback.Appreciate that.
      My quick comments,
      1. You mentioned about the error could you please share those if possible.
      2. Please use dotnet-svccutil.exe (and not the svcutil.exe which works with old .NET)
      3. If you own those ASMX services (including contract and definition) then use of ChannelFactory instead of Proxy generation is preferred.

      Please do share more details on the error. Thank you.

  7. I have VS2017 15.4.5 and had issue with creating client code using Connected service. Using svcutil global tool was able to achieve it !! Thanks for very good article.

  8. Thanks for clarifying on Connected services plugin. I am facing similar issues on one of my WCF service and using VS2017(15.4).I shall try 2nd option though anyway. thank you again.

Comments are closed.