.Net Sample
Add authentication information to request headers
GetHttpClient(), GetAsync(),GetAsyncCall() are defined in WebAPIProxy class
Sample:
private string baseAddress = “http://demo-api.fmpilot2.com/Internal/api/”
private const string authTokenKey = "authenticationToken";
private const string clientKey = "callingClient";
private const string domainKey = "actingDomain";
private HttpClient GetHttpClient(string authTokenValue, string clientValue, string domainValue, string contentType)
{
HttpClient client = new HttpClient();
// Set the Header values
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add(authTokenKey, authTokenValue);
client.DefaultRequestHeaders.Add(clientKey, clientValue);
client.DefaultRequestHeaders.Add(domainKey, domainValue);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
// Set the base address
client.BaseAddress = new Uri(baseAddress);
return client;
}
Creating Result Class
Sample:
public class States
{
public string Id { get; set; }
public string Name { get; set; }
}
Executing StateLookup(GET api/Values/StateLookup)
Sample:
WebAPIProxy webAPIProxy = new WebAPIProxy();
WebApiResult List<States> result = webAPIProxy.GetAsync List<States> (authTokenValue, sourceDomainValue, domainValue, "Values/StateLookup", "application/json");
public WebApiResult<T> GetAsync<T>(string authTokenValue, string clientValue, string domainValue, string actionName, string contentType)
{
WebApiResult<T> output = new WebApiResult<T>();
try
{
var result = GetAsyncCall<T>(authTokenValue, clientValue, domainValue, actionName, contentType);
result.Wait();
return result.Result;
}
catch(Exception e)
{
output.StatusCode = System.Net.HttpStatusCode.InternalServerError;
output.ErrorMessage = NoErrorMessage;
return output;
}
}
private async Task<WebApiResult <T>> GetAsyncCall<T>(string authTokenValue, string clientValue, string domainValue, string actionName, string contentType)
{
Func<Task<WebApiResult<T>>> valueFactory = async () =>
{
WebApiResult<T> output = new WebApiResult<T>();
HttpClient client = GetHttpClient(authTokenValue, clientValue, domainValue, contentType);
HttpResponseMessage response = await client.GetAsync(actionName).ConfigureAwait(false);
output.StatusCode = response.StatusCode;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
output.Result = await response.Content.ReadAsAsync<T>();
else
{
output.ErrorMessage = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(output.ErrorMessage))
{
output.ErrorMessage = NoErrorMessage;
}
}
return output;
}
};