HttpClient
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.
async Task<int> GetResultUsingHttpClient() { Uri uri = new Uri("http://localhost/api/Algebra /DoAlgebra?num1=3&num2=4"); string message = string.Empty; using (var client = new HttpClient()) { client.BaseAddress = uri; client.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); var content = new StringContent("", Encoding.UTF8); var response = await client.PostAsync(uri, content); message = await response.Content.ReadAsStringAsync(); } var serializer = new JavaScriptSerializer(); var result = serializer.Deserialize<AlgebraResult>(message); return result.AddResult; }
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.
int GetResultUsingWCFChannel() { Uri uri = new Uri("http://localhost/AlgebraApi/api/Algebra"); var binding = new WebHttpBinding(); var factory = new WebChannelFactory<IAlgebraController>(binding, uri); var proxy = factory.CreateChannel(); var result = proxy.DoAlgebra(3, 4); return result.AddResult; }
Using the WCF client, we call an interface method to invoke the API. Define the interface IAlgebraController
as a ServiceContract
.
[ServiceContract] public interface IAlgebraController { [OperationContract] [WebInvoke(BodyStyle=WebMessageBodyStyle.Bare, ResponseFormat=WebMessageFormat.Xml, UriTemplate="DoAlgebra?num1={num1}&num2={num2}")] AlgebraResult DoAlgebra(int num1, int num2); }
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.
Can you share a way for calling(Get method) rest service from WCF and serialising the result