Hi Ton,
What I actually did is re-write my API client and used the WebServerClient as my base class like this:
public class MyApiClient : WebServerClient
This builds in a lot of the required functionality into your client without needing to repeat code (I'm also guessing this is the reason that WebServerClient isn't a sealed class). Once you have this inheritance set up you can do this in your client code:
private static readonly AuthorizationServerDescription MyApiDescription = new AuthorizationServerDescription
{
TokenEndpoint = new Uri(ConfigurationManager.AppSettings["ApiTokenUrl"].ToString(CultureInfo.InvariantCulture)),
AuthorizationEndpoint = new Uri(ConfigurationManager.AppSettings["ApiAuthorizeUrl"].ToString(CultureInfo.InvariantCulture))
};
private readonly IAuthorizationState _authorizationState;
Then in your methods within your client code you can do this:
For synchronous methods you can do this:
using (var httpClient = new HttpClient(CreateAuthorizingHandler(_authorizationState)))
{
var response = httpClient.GetAsync(ApiRootUrl + "stuff/range/" +
start.ToString(DateService.DefaultDateFormatString) +
"/" +
end.ToString(DateService.DefaultDateFormatString)).Result;
var responsecontent = response.Content;
return responsecontent.ReadAsAsync<List<MyClass>>().Result;
}
Even though HttpClient is more or less inherantly Asynchronous including the .Result calls turns them into synchronous calls, I've done this as a lot of these methods are called via my controllers but using Ajax on the client so the blocking behavior isn't an issue.
If you wanted to implement this Async you would do it like this:
public async Task<List<MyClass>> GetStuffAsync(DateTime start, DateTime end,
CancellationToken cancelToken =
default(CancellationToken))
{
using (var httpClient = new HttpClient(CreateAuthorizingHandler(_authorizationState)))
{
var response = await httpClient.GetAsync(ApiRootUrl + "stuff/range/" +
start.ToString(DateService.DefaultDateFormatString) +
"/" +
end.ToString(DateService.DefaultDateFormatString), cancelToken);
return (await response.Content.ReadAsAsync<List<MyClass>>());