|
|
using log4net; using Newtonsoft.Json; using NPOI.SS.Formula.Functions; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Text;
namespace CounsellorBL.Helper { public class APIHelper { private static ILog _inst = null; private static ILog Logger { get { if (_inst == null) { _inst = LogManager.GetLogger(typeof(APIHelper)); } return _inst; } }
#region 類別
/// <summary>
/// 基本回傳資料
/// </summary>
public class BaseHttpStatus { public string message { get; set; } public int status { get; set; } }
/// <summary>
/// 資料內容
/// </summary>
public class DataContent { public string Key { get; set; } public Type Type { get; set; } public object Content { get; set; } public bool ShowLog { get; set; } public DataContent() { ShowLog = true; } } #endregion
/// <summary>
/// POST
/// </summary>
/// <param name="i_sUrl">網址</param>
/// <param name="clientAction">HttpClient設定</param>
/// <param name="dataContents">FormData內容</param>
/// <param name="responseMessage">回傳的訊息</param>
public static string BasePost(string i_sUrl, Action<HttpClient> clientAction, dynamic dataContents, out HttpResponseMessage o_hrmResult, string type = null) { string sMsg = null; HttpResponseMessage hrmResult = null; try { // 紀錄LOG
var source = new StackTrace().GetFrame(1).GetMethod(); var logs = new List<string>() { $"來源:{source.ReflectedType?.FullName ?? nameof(BasePost)}.{source.Name?? "undefined"}" };
// 送出資料
using (var client = new HttpClient()) { if (clientAction != null) { clientAction.Invoke(client); } HttpContent requestData = null; if (type == null) { var formData = new MultipartFormDataContent();
// 將參數存入並記錄LOG
var lsContent = dataContents as List<DataContent>; if (lsContent != null && lsContent.Any()) { var parameterLogs = new List<string>(); foreach (var dataContent in lsContent) { // 根據參數類型存入formData
object parameterValue; if (dataContent.Type == typeof(StringContent)) { var value = dataContent.Content as string; formData.Add(new StringContent(value), dataContent.Key); parameterValue = value; } else if (dataContent.Type == typeof(StreamContent)) { var value = dataContent.Content as string; formData.Add(new StreamContent(new MemoryStream(File.ReadAllBytes(value))), dataContent.Key, Path.GetFileName(value)); parameterValue = value; } else if (dataContent.Type == typeof(ByteArrayContent)) { var value = dataContent.Content as byte[]; formData.Add(new ByteArrayContent(value), dataContent.Key); parameterValue = value.Length; } else { parameterValue = "無法辨識類型"; }
// 根據設定決定是否存入Log
if (dataContent.ShowLog) { parameterLogs.Add($"{dataContent.Key}:{parameterValue}"); } }
// 紀錄LOG
if (parameterLogs.Any()) { logs.Add($"參數:{string.Join(", ", parameterLogs)}"); } requestData = formData; } } else { requestData = new StringContent(JsonConvert.SerializeObject(dataContents), Encoding.UTF8, "application/json"); logs.Add($"jsonBody:{dataContents}"); }
// 將資料送出並記錄LOG
logs.Add($"網址:{i_sUrl}"); Logger.Info($"網址:{i_sUrl}"); hrmResult = client.PostAsync(i_sUrl, requestData).Result;
// 儲存LOG
if (hrmResult.IsSuccessStatusCode) { logs.Insert(0, "POST成功"); Logger.Info(string.Join(",", logs)); } else { Logger.Error($"BasePost Fail"); string sErrorMessage = $"ReasonPhrase:{hrmResult.ReasonPhrase} hrmResult.Headers.WwwAuthenticate:{hrmResult.Headers.WwwAuthenticate} "; sMsg = sErrorMessage; logs.Insert(0, $"POST失敗(狀態:{hrmResult.StatusCode},錯誤訊息:{sErrorMessage})"); Logger.Error(string.Join(",", logs)); } Logger.Info(JsonConvert.SerializeObject(hrmResult.Headers));
}
} catch (Exception ex) { sMsg = ex.Message; }
o_hrmResult = hrmResult; return sMsg; }
/// <summary>
/// Get
/// </summary>
/// <param name="uri">網址</param>
/// <param name="clientAction">HttpClient設定</param>
/// <param name="dataContents">FormData內容</param>
/// <param name="responseMessage">回傳的訊息</param>
public static void BaseGet(string uri, Action<HttpClient> clientAction, Dictionary<string, string> dataContents, out HttpResponseMessage responseMessage) { // 紀錄LOG
var source = new StackTrace().GetFrame(1).GetMethod(); var logs = new List<string> { $"來源:{source.ReflectedType?.FullName ?? nameof(BasePost)}.{source.Name?? "undefined"}" };
// 送出資料
using (var client = new HttpClient()) { if (clientAction != null) { clientAction.Invoke(client); } List<string> stringData = new List<string> { }; // 將參數存入並記錄LOG
if (dataContents.Any()) { foreach (var dataContent in dataContents) { stringData.Add(string.Format("{0}={1}", dataContent.Key, dataContent.Value)); } } // 將資料送出並記錄LOG
uri = string.Format("{0}{1}", uri, dataContents.Any() ? string.Join("&", stringData) : null);
responseMessage = client.GetAsync(uri).Result;
logs.Add(string.Format("網址:{0}", uri));
// 儲存LOG
if (responseMessage.IsSuccessStatusCode) { logs.Insert(0, "GET成功"); Logger.Info(string.Join(",", logs)); } else { var errorMessage = "錯誤訊息無法辨識"; if (responseMessage.Content.Headers.ContentType.MediaType.Contains("json")) { errorMessage = JsonConvert.DeserializeObject<BaseHttpStatus>(responseMessage.Content.ReadAsStringAsync().Result).message; } logs.Insert(0, string.Format("POST失敗(狀態:{0},錯誤訊息:{1})", responseMessage.StatusCode, errorMessage)); Logger.Error(string.Join(",", logs)); } Logger.Info(JsonConvert.SerializeObject(responseMessage.Headers)); } }
} }
|