You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

235 lines
9.1 KiB

  1. using log4net;
  2. using Newtonsoft.Json;
  3. using NPOI.SS.Formula.Functions;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net.Http;
  10. using System.Text;
  11. namespace CounsellorBL.Helper
  12. {
  13. public class APIHelper
  14. {
  15. private static ILog _inst = null;
  16. private static ILog Logger
  17. {
  18. get
  19. {
  20. if (_inst == null)
  21. {
  22. _inst = LogManager.GetLogger(typeof(APIHelper));
  23. }
  24. return _inst;
  25. }
  26. }
  27. #region 類別
  28. /// <summary>
  29. /// 基本回傳資料
  30. /// </summary>
  31. public class BaseHttpStatus
  32. {
  33. public string message { get; set; }
  34. public int status { get; set; }
  35. }
  36. /// <summary>
  37. /// 資料內容
  38. /// </summary>
  39. public class DataContent
  40. {
  41. public string Key { get; set; }
  42. public Type Type { get; set; }
  43. public object Content { get; set; }
  44. public bool ShowLog { get; set; }
  45. public DataContent()
  46. {
  47. ShowLog = true;
  48. }
  49. }
  50. #endregion
  51. /// <summary>
  52. /// POST
  53. /// </summary>
  54. /// <param name="i_sUrl">網址</param>
  55. /// <param name="clientAction">HttpClient設定</param>
  56. /// <param name="dataContents">FormData內容</param>
  57. /// <param name="responseMessage">回傳的訊息</param>
  58. public static string BasePost(string i_sUrl, Action<HttpClient> clientAction, dynamic dataContents, out HttpResponseMessage o_hrmResult, string type = null)
  59. {
  60. string sMsg = null;
  61. HttpResponseMessage hrmResult = null;
  62. try
  63. {
  64. // 紀錄LOG
  65. var source = new StackTrace().GetFrame(1).GetMethod();
  66. var logs = new List<string>()
  67. {
  68. $"來源:{source.ReflectedType?.FullName ?? nameof(BasePost)}.{source.Name?? "undefined"}"
  69. };
  70. // 送出資料
  71. using (var client = new HttpClient())
  72. {
  73. if (clientAction != null)
  74. {
  75. clientAction.Invoke(client);
  76. }
  77. HttpContent requestData = null;
  78. if (type == null)
  79. {
  80. var formData = new MultipartFormDataContent();
  81. // 將參數存入並記錄LOG
  82. var lsContent = dataContents as List<DataContent>;
  83. if (lsContent != null && lsContent.Any())
  84. {
  85. var parameterLogs = new List<string>();
  86. foreach (var dataContent in lsContent)
  87. {
  88. // 根據參數類型存入formData
  89. object parameterValue;
  90. if (dataContent.Type == typeof(StringContent))
  91. {
  92. var value = dataContent.Content as string;
  93. formData.Add(new StringContent(value), dataContent.Key);
  94. parameterValue = value;
  95. }
  96. else if (dataContent.Type == typeof(StreamContent))
  97. {
  98. var value = dataContent.Content as string;
  99. formData.Add(new StreamContent(new MemoryStream(File.ReadAllBytes(value))), dataContent.Key, Path.GetFileName(value));
  100. parameterValue = value;
  101. }
  102. else if (dataContent.Type == typeof(ByteArrayContent))
  103. {
  104. var value = dataContent.Content as byte[];
  105. formData.Add(new ByteArrayContent(value), dataContent.Key);
  106. parameterValue = value.Length;
  107. }
  108. else
  109. {
  110. parameterValue = "無法辨識類型";
  111. }
  112. // 根據設定決定是否存入Log
  113. if (dataContent.ShowLog)
  114. {
  115. parameterLogs.Add($"{dataContent.Key}:{parameterValue}");
  116. }
  117. }
  118. // 紀錄LOG
  119. if (parameterLogs.Any())
  120. {
  121. logs.Add($"參數:{string.Join(", ", parameterLogs)}");
  122. }
  123. requestData = formData;
  124. }
  125. }
  126. else
  127. {
  128. requestData = new StringContent(JsonConvert.SerializeObject(dataContents), Encoding.UTF8, "application/json");
  129. logs.Add($"jsonBody:{dataContents}");
  130. }
  131. // 將資料送出並記錄LOG
  132. logs.Add($"網址:{i_sUrl}");
  133. Logger.Info($"網址:{i_sUrl}");
  134. hrmResult = client.PostAsync(i_sUrl, requestData).Result;
  135. // 儲存LOG
  136. if (hrmResult.IsSuccessStatusCode)
  137. {
  138. logs.Insert(0, "POST成功");
  139. Logger.Info(string.Join(",", logs));
  140. }
  141. else
  142. {
  143. Logger.Error($"BasePost Fail");
  144. string sErrorMessage = $"ReasonPhrase:{hrmResult.ReasonPhrase} hrmResult.Headers.WwwAuthenticate:{hrmResult.Headers.WwwAuthenticate} ";
  145. sMsg = sErrorMessage;
  146. logs.Insert(0, $"POST失敗(狀態:{hrmResult.StatusCode},錯誤訊息:{sErrorMessage})");
  147. Logger.Error(string.Join(",", logs));
  148. }
  149. Logger.Info(JsonConvert.SerializeObject(hrmResult.Headers));
  150. }
  151. }
  152. catch (Exception ex)
  153. {
  154. sMsg = ex.Message;
  155. }
  156. o_hrmResult = hrmResult;
  157. return sMsg;
  158. }
  159. /// <summary>
  160. /// Get
  161. /// </summary>
  162. /// <param name="uri">網址</param>
  163. /// <param name="clientAction">HttpClient設定</param>
  164. /// <param name="dataContents">FormData內容</param>
  165. /// <param name="responseMessage">回傳的訊息</param>
  166. public static void BaseGet(string uri, Action<HttpClient> clientAction, Dictionary<string, string> dataContents, out HttpResponseMessage responseMessage)
  167. {
  168. // 紀錄LOG
  169. var source = new StackTrace().GetFrame(1).GetMethod();
  170. var logs = new List<string>
  171. {
  172. $"來源:{source.ReflectedType?.FullName ?? nameof(BasePost)}.{source.Name?? "undefined"}"
  173. };
  174. // 送出資料
  175. using (var client = new HttpClient())
  176. {
  177. if (clientAction != null)
  178. {
  179. clientAction.Invoke(client);
  180. }
  181. List<string> stringData = new List<string> { };
  182. // 將參數存入並記錄LOG
  183. if (dataContents.Any())
  184. {
  185. foreach (var dataContent in dataContents)
  186. {
  187. stringData.Add(string.Format("{0}={1}", dataContent.Key, dataContent.Value));
  188. }
  189. }
  190. // 將資料送出並記錄LOG
  191. uri = string.Format("{0}{1}", uri, dataContents.Any() ? string.Join("&", stringData) : null);
  192. responseMessage = client.GetAsync(uri).Result;
  193. logs.Add(string.Format("網址:{0}", uri));
  194. // 儲存LOG
  195. if (responseMessage.IsSuccessStatusCode)
  196. {
  197. logs.Insert(0, "GET成功");
  198. Logger.Info(string.Join(",", logs));
  199. }
  200. else
  201. {
  202. var errorMessage = "錯誤訊息無法辨識";
  203. if (responseMessage.Content.Headers.ContentType.MediaType.Contains("json"))
  204. {
  205. errorMessage = JsonConvert.DeserializeObject<BaseHttpStatus>(responseMessage.Content.ReadAsStringAsync().Result).message;
  206. }
  207. logs.Insert(0, string.Format("POST失敗(狀態:{0},錯誤訊息:{1})", responseMessage.StatusCode, errorMessage));
  208. Logger.Error(string.Join(",", logs));
  209. }
  210. Logger.Info(JsonConvert.SerializeObject(responseMessage.Headers));
  211. }
  212. }
  213. }
  214. }