WCF Client: How to Create and Use It
In this article
To create and use a Windows Communication Foundation (WCF) client, you generate a proxy class from the service's metadata (using Visual Studio's Add Service Reference or the svcutil.exe tool), then instantiate that proxy, call its methods, and close it properly. This guide walks you through the process step by step, assuming you have a WCF service already running and accessible.
What You'll Need
- Visual Studio (any recent edition) or the .NET SDK with the
svcutil.exetool installed. - The URL of a running WCF service, or its WSDL/metadata document.
- Basic familiarity with C# and project creation in Visual Studio.
Step-by-Step
- Create a client project. Open Visual Studio and create a new Console App (.NET Framework) or Class Library project. For .NET Core or .NET 5+, you'll need the System.ServiceModel.Http NuGet package instead of the built-in WCF client.
- Add a service reference. In Solution Explorer, right-click the project and choose Add > Service Reference (or Connected Service in newer Visual Studio versions). Enter the service URL in the address field and click Go. Visual Studio will discover the service and display its operations. Give the namespace a meaningful name and click OK.
- Alternatively, use svcutil.exe. Open a Developer Command Prompt and run:
svcutil.exe http://your-service-url?wsdl. This generates a .cs file and a config file. Add both to your project. - Configure the endpoint. If you used Add Service Reference, the necessary bindings and endpoint information are added to your App.config or Web.config automatically. Verify the
<system.serviceModel>section contains a<client>element with the correct endpoint address and binding. - Instantiate the client. In your code, create an instance of the generated client class (usually named YourServiceClient). For example:
var client = new MyServiceClient(); - Call service operations. Invoke methods on the client object as you would any other method. For example:
var result = client.GetData(42); Console.WriteLine(result); - Close the client properly. Always close or abort the client to release resources. Use a try/catch/finally block:
In C# 8+, you can usetry { client.Close(); } catch { client.Abort(); throw; }usingdeclarations if the client implementsIDisposable, but be aware that disposing may throw if the channel is faulted. - Handle exceptions. WCF throws
CommunicationException,TimeoutException, andFaultException. Catch these to handle network issues or service faults gracefully. - Run and test. Build and run your client project. Ensure the service is running and reachable. Check the output for expected results.
Common Mistakes
- Forgetting to close the client. Leaving the client open can exhaust connections and cause timeouts. Always close or abort in a finally block.
- Using the wrong binding. If the service uses wsHttpBinding but your client config specifies basicHttpBinding, calls will fail. Match the binding to the service's configuration.
- Ignoring security settings. Many services require transport or message security. If your client config lacks the correct security mode, you'll get authentication errors.
- Not updating the reference after service changes. If the service contract changes, you must refresh the service reference (right-click > Update Service Reference) to regenerate the proxy.
- Assuming .NET Core support is identical. The WCF client in .NET Core/.NET 5+ supports only a subset of bindings and features. Check compatibility before migrating.
Tips
- Use
svcutil.exewith the/configswitch to generate a config file separately, which helps when you need to tweak settings. - Enable
includeExceptionDetailInFaultson the service side during development to get detailed error messages. - Consider using
ChannelFactory<T>for a lighter-weight client if you don't need the generated proxy class. - Keep your client configuration in App.config (for desktop apps) or Web.config (for web apps) and avoid hardcoding endpoints in code.
- Test with the WCF Test Client (wcftestclient.exe) to verify the service works before writing client code.
Troubleshooting
If your client fails to connect, work through these checks in order:
- Verify the service is running. Open the service URL in a browser; you should see the metadata help page.
- Check the endpoint address. Ensure the address in your config matches the actual service URL, including the port and path.
- Confirm the binding and security match. Compare the
<binding>and<security>settings in your client config with the service's config. - Enable tracing. Add a
<system.diagnostics>section to your config to log WCF messages and errors. Use the Service Trace Viewer tool to read the logs. - Check firewall and network access. Ensure the port is open and the service is reachable from your machine.
- Rebuild the proxy. Delete the existing service reference and add it again to rule out stale metadata.
If none of that works, search the exact exception message along with the binding name; WCF errors are often specific and well-documented.
Frequently Asked Questions
Can I use a WCF client in .NET Core or .NET 5+?
Yes, but only with the System.ServiceModel.Http NuGet package, and only a subset of bindings and features are supported. BasicHttpBinding and some security modes work; others do not.
What is the difference between Close() and Abort()?
Close() gracefully shuts down the channel and may throw if the channel is faulted. Abort() immediately terminates the channel without throwing, and is safe to call even after a fault.
Do I need to regenerate the proxy every time the service changes?
Yes, if the service contract (operations, data contracts) changes. Use Update Service Reference in Visual Studio or rerun svcutil.exe.
How do I pass credentials to the service?
Set the ClientCredentials property on the client instance before calling operations. The exact type depends on the security mode (e.g., UserName, Windows, Certificate).
Why do I get a timeout exception?
Timeouts often mean the service is slow, unreachable, or the binding's sendTimeout or receiveTimeout is too short. Increase the timeout values in the binding configuration and verify network connectivity.
Can I call a WCF service from a non-.NET application?
Yes, if the service uses HTTP-based bindings like BasicHttpBinding, you can call it from any platform that supports SOAP over HTTP. Other bindings may require .NET.