The typical way to access a REST API is using the HttpClient. Create a HttpClient object. Pass in request headers. Call the PostAsync method with the URL and the request body. Use await keyword to wait for the response. Get the message as a JSON string. Use JavaScriptSerializer to convert the JSON to a C# object.

WCF Client

The alternate way to access a REST client is using WCF. WCF offers webHttpBinding which is used to access any REST API. The WebChannelFactory class uses a ServiceContract interface as template. It accepts the binding and the URL information to create a factory object. The factory object creates the client proxy. Call the DoAlgebra method on the proxy.

Using the WCF client, we call an interface method to invoke the API. Define the interface IAlgebraController as a ServiceContract.

Decorate the method with an OperationContract attribute. And WebInvoke attribute. The UriTemplate property has the request URL.

I prefer the WCF client to call an API. Using WCF client, we use an interface method to do a POST operation. This is much better than using HttpClient. The WCF Client approach makes it easy to write unit tests for the code.

Alternate way to invoke a REST API using WCF
Tagged on: