-
Notifications
You must be signed in to change notification settings - Fork 38
Using the Client API
Each generated client API class has an constructor of injecting a HttpClient instance and a base URI of the Web service.
public partial class SuperDemo
{
private System.Net.Http.HttpClient client;
private System.Uri baseUri;
public SuperDemo(System.Net.Http.HttpClient client, System.Uri baseUri)
{
this.client = client;
this.baseUri = baseUri;
}
public async Task<System.Int32> GetIntSquareAsync(int d)
{
var template = new System.UriTemplate("api/SuperDemo/int?d={d}");
var uriParameters = new System.Collections.Specialized.NameValueCollection();
uriParameters.Add("d", d.ToString());
var requestUri = template.BindByName(this.baseUri, uriParameters);
var responseMessage = await client.GetAsync(requestUri.ToString());
responseMessage.EnsureSuccessStatusCode();
var text = await responseMessage.Content.ReadAsStringAsync();
return System.Int32.Parse(text);
}
...
This gives you to flexibility of initializing the HttpClient instance with proper credentials, typically with a bearer token. Generally 1 desktop application just needs 1 instance of HttpClient which well supports concurrent calls.
In case of Http errors, the client codes should catch exceptions that could be thrown by "responseMessage.EnsureSuccessStatusCode();" in the implementation of the client API.
The generated client API supports all Action Results in Web API 2, and particularly provides conveniences for "Other Return Types" which could be built-in .NET types and custom complex types. For IHttpActionResult, the return type in client API is HttpResponseMessage.
Examples of client programs using the generated client API:
- Super Demo talks to Web API SuperDemo
- Complex Type Examples talks to Web API Entities. Please note that TestCreatePeopleConcurrently() makes 100 concurrent calls.
So using the generated client API is very similar to using the client proxy classes generated by SvcUtil.exe in WCF.