using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace STAFF_API.Services { public class WebAPIClient : IWebAPIClient { #region Private Properties private HttpClient _client; // To assign access token & additional headers private HttpClient APIClient { get { if(_client == null) _client = new HttpClient(); if(_client.BaseAddress == null) _client.BaseAddress = new Uri(this.BaseAddress); // Clear existing header _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (this.Headers != null) { foreach (KeyValuePair header in Headers) _client.DefaultRequestHeaders.Add(header.Key, header.Value.ToString()); } // Assign token if (!string.IsNullOrEmpty(this.AccessToken)) _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken); return _client; } } #endregion #region Public Properties /// /// Specify base address to use on http client /// public string BaseAddress { get; set; } /// /// Access token to call web api /// public string AccessToken { get; set; } public Dictionary Headers { get; set; } #endregion /// /// /// public WebAPIClient() { } #region Private Functions #endregion #region Public Functions /// /// Call web api with HTTP GET method /// /// /// The part of the web api serevice. /// /// Return as generic class public async Task GetAsync(string actionPart) { try { var client = this.APIClient; HttpResponseMessage response = await client.GetAsync(actionPart); if (response.IsSuccessStatusCode) { var jsonString = await response.Content.ReadAsStringAsync(); try { return JsonConvert.DeserializeObject(jsonString); } catch (Exception) { // Return null if T is a reference type (or a nullable value type), 0 for int, '\0' for char return default(T); } } else throw new InvalidOperationException(response.ReasonPhrase); } catch (Exception ex) { throw ex; } } /// /// Call web api with HTTP POST method /// /// /// The part of the web api serevice. /// /// Input to call web api /// Return as generic class public async Task PostAsync(string actionPart, object inputModel) { try { var client = this.APIClient; var param = Newtonsoft.Json.JsonConvert.SerializeObject(inputModel); HttpContent contentPost = new StringContent(param, null, "application/json"); HttpResponseMessage response = await client.PostAsync(actionPart, contentPost); if (response.IsSuccessStatusCode) { var jsonString = await response.Content.ReadAsStringAsync(); try { return JsonConvert.DeserializeObject(jsonString); } catch (Exception) { // Return null if T is a reference type (or a nullable value type), 0 for int, '\0' for char return default(T); } } else throw new InvalidOperationException(response.ReasonPhrase); } catch (Exception ex) { throw ex; } } /// /// Call web api with HTTP POST method with file uploading /// /// /// The part of the web api serevice. /// /// Multipart Form Data Content /// Return as generic class public async Task PostFileAsync(string actionPart, MultipartFormDataContent formData) { var client = this.APIClient; try { HttpResponseMessage response = await client.PostAsync(actionPart, formData); if (response.IsSuccessStatusCode) { var jsonString = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(jsonString); } else { string x = await response.Content.ReadAsStringAsync(); throw new InvalidOperationException(x); } } finally { // Clear all stream. formData.Dispose(); } } /// /// Call web api with HTTP POST method with file uploading /// /// The part of the web api serevice. /// /// Input to call web api /// Expected file downloaded path /// Return file download path public async Task PostDownloadAsync(string actionPart, object inputModel, string returnPhysicalFilePath) { try { var client = this.APIClient; //Set post body parameters var param = Newtonsoft.Json.JsonConvert.SerializeObject(inputModel); HttpContent contentPost = new StringContent(param, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(actionPart, contentPost); if (response.IsSuccessStatusCode) { if (File.Exists(returnPhysicalFilePath)) File.Delete(returnPhysicalFilePath); // Read response asynchronously and save asynchronously to file using (FileStream fileStream = new FileStream(returnPhysicalFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) { //copy the content from response to filestream await response.Content.CopyToAsync(fileStream); } return returnPhysicalFilePath; } else { throw new FileNotFoundException(); } } catch (Exception ex) { throw ex; } } /// /// Call web api with HTTP Put method /// /// /// The part of the web api serevice. /// /// Input to call web api /// Return as generic class public async Task PutAsync(string actionPart, object inputModel) { try { var client = this.APIClient; //Set post body parameters var param = Newtonsoft.Json.JsonConvert.SerializeObject(inputModel); HttpContent contentPut = new StringContent(param, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PutAsync(actionPart, contentPut); if (response.IsSuccessStatusCode) { var jsonString = await response.Content.ReadAsStringAsync(); try { return JsonConvert.DeserializeObject(jsonString); } catch (Exception) { // Return null if T is a reference type (or a nullable value type), 0 for int, '\0' for char return default(T); } } else throw new InvalidOperationException(response.ReasonPhrase); } catch (Exception ex) { throw ex; } } /// /// Call web api with HTTP Delete method /// /// /// The part of the web api serevice. /// /// public async Task DeleteAsync(string actionPart) { try { var client = this.APIClient; HttpResponseMessage response = await client.DeleteAsync(actionPart); if (response.IsSuccessStatusCode) { var jsonString = await response.Content.ReadAsStringAsync(); try { return JsonConvert.DeserializeObject(jsonString); } catch (Exception) { // Return null if T is a reference type (or a nullable value type), 0 for int, '\0' for char return default(T); } } else throw new InvalidOperationException(response.ReasonPhrase); } catch (Exception ex) { throw ex; } } #endregion } }