324 lines
11 KiB
C#
324 lines
11 KiB
C#
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<string, string> 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
|
|
|
|
/// <summary>
|
|
/// Specify base address to use on http client
|
|
/// </summary>
|
|
public string BaseAddress { get; set; }
|
|
|
|
/// <summary>
|
|
/// Access token to call web api
|
|
/// </summary>
|
|
public string AccessToken { get; set; }
|
|
|
|
public Dictionary<string, string> Headers { get; set; }
|
|
|
|
#endregion
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public WebAPIClient()
|
|
{
|
|
}
|
|
|
|
#region Private Functions
|
|
#endregion
|
|
|
|
#region Public Functions
|
|
/// <summary>
|
|
/// Call web api with HTTP GET method
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="actionPart">The part of the web api serevice.
|
|
/// </param>
|
|
/// <returns>Return as generic class</returns>
|
|
public async Task<T> GetAsync<T>(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<T>(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;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Call web api with HTTP POST method
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="actionPart">The part of the web api serevice.
|
|
/// </param>
|
|
/// <param name="inputModel">Input to call web api</param>
|
|
/// <returns>Return as generic class</returns>
|
|
public async Task<T> PostAsync<T>(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<T>(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;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Call web api with HTTP POST method with file uploading
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="actionPart">The part of the web api serevice.
|
|
///</param>
|
|
/// <param name="formData">Multipart Form Data Content</param>
|
|
/// <returns>Return as generic class</returns>
|
|
public async Task<T> PostFileAsync<T>(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<T>(jsonString);
|
|
}
|
|
|
|
else
|
|
{
|
|
string x = await response.Content.ReadAsStringAsync();
|
|
throw new InvalidOperationException(x);
|
|
}
|
|
|
|
}
|
|
finally
|
|
{
|
|
// Clear all stream.
|
|
formData.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Call web api with HTTP POST method with file uploading
|
|
/// </summary>
|
|
/// <param name="actionPart">The part of the web api serevice.
|
|
///</param>
|
|
/// <param name="inputModel">Input to call web api</param>
|
|
/// <param name="returnPhysicalFilePath">Expected file downloaded path</param>
|
|
/// <returns>Return file download path</returns>
|
|
public async Task<string> 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;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Call web api with HTTP Put method
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="actionPart">The part of the web api serevice.
|
|
/// </param>
|
|
/// <param name="inputModel">Input to call web api</param>
|
|
/// <returns>Return as generic class</returns>
|
|
public async Task<T> PutAsync<T>(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<T>(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;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Call web api with HTTP Delete method
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="actionPart">The part of the web api serevice.
|
|
/// </param>
|
|
/// <returns></returns>
|
|
public async Task<T> DeleteAsync<T>(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<T>(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
|
|
}
|
|
}
|