/// <summary> /// 從網路取得相對應WebAPI的資料 /// </summary> /// <param name="dic">所要傳遞的參數 Dictionary </param> /// <param name="httpMethod">Get Or Post</param> /// <returns></returns> protected virtual async Task <APIResult> SendAsync(Dictionary <string, string> dic, HttpMethod httpMethod, CancellationToken cancellationTokentoken = default(CancellationToken)) { this.ServiceResult = new APIResult(); APIResult apiResult = this.ServiceResult; string jsonPayload = ""; #region 確認網路已經連線 if (await UtilityHelper.CanConnectRemoteHostService() == false) { apiResult.Status = false; apiResult.Message = "無網路連線可用 或者 無法連線到遠端主機,請檢查網路狀態與主機服務是否可以使用"; return(apiResult); } #endregion //檢查網路狀態 if (UtilityHelper.IsConnected() == false) { apiResult.Status = false; apiResult.Message = "無網路連線可用,請檢查網路狀態"; return(apiResult); } if (dic.ContainsKey(LOBGlobal.JSONDataKeyName)) { jsonPayload = dic[LOBGlobal.JSONDataKeyName]; dic.Remove(LOBGlobal.JSONDataKeyName); } HttpClientHandler handler = new HttpClientHandler(); using (HttpClient client = new HttpClient()) { try { //client.Timeout = TimeSpan.FromSeconds(5); string queryString = dic.ToQueryString(); string endPoint = $"{Host}{Url}/{Route}" + queryString; UriBuilder ub = new UriBuilder(endPoint); HttpResponseMessage response = null; if (string.IsNullOrEmpty(this.Token) == false) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.Token); } #region Get Or Post if (httpMethod == HttpMethod.Get) { // 使用 Get 方式來呼叫 response = await client.GetAsync(ub.Uri, cancellationTokentoken); } else if (httpMethod == HttpMethod.Post) { // 使用 Post 方式來呼叫 if (EnctypeMethod == EnctypeMethod.FORMURLENCODED) { // 使用 FormUrlEncoded 方式來進行傳遞資料的編碼 response = await client.PostAsync(ub.Uri, dic.ToFormUrlEncodedContent(), cancellationTokentoken); } else if (EnctypeMethod == EnctypeMethod.JSON) { client.DefaultRequestHeaders.Accept.TryParseAdd("application/json"); response = await client.PostAsync(ub.Uri, new StringContent(jsonPayload, Encoding.UTF8, "application/json"), cancellationTokentoken); } } else if (httpMethod == HttpMethod.Put) { // 使用 Post 方式來呼叫 if (EnctypeMethod == EnctypeMethod.FORMURLENCODED) { // 使用 FormUrlEncoded 方式來進行傳遞資料的編碼 response = await client.PutAsync(ub.Uri, dic.ToFormUrlEncodedContent(), cancellationTokentoken); } else if (EnctypeMethod == EnctypeMethod.JSON) { client.DefaultRequestHeaders.Accept.TryParseAdd("application/json"); response = await client.PutAsync(ub.Uri, new StringContent(jsonPayload, Encoding.UTF8, "application/json"), cancellationTokentoken); } } else if (httpMethod == HttpMethod.Delete) { response = await client.DeleteAsync(ub.Uri, cancellationTokentoken); } else { throw new NotImplementedException("Not Found HttpMethod"); } #endregion #region Response if (response != null) { String strResult = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode == true) { #region 回傳成功狀態碼 apiResult = JsonConvert.DeserializeObject <APIResult>(strResult, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore }); if (apiResult.Status == true) { var fooDataString = apiResult.Payload == null?"": apiResult.Payload.ToString(); if (ApiResultIsCollection == false) { SingleItem = JsonConvert.DeserializeObject <T>(fooDataString, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore }); if (ApiResultIsCollection == false && PersistentStorage == PersistentStorage.Single) { if (SingleItem == null) { SingleItem = (T)Activator.CreateInstance(typeof(T)); } await this.WriteToFileAsync(); } } else { Items = JsonConvert.DeserializeObject <List <T> >(fooDataString, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore }); if (ApiResultIsCollection == true && PersistentStorage == PersistentStorage.Collection) { if (Items == null) { Items = (List <T>)Activator.CreateInstance(typeof(List <T>)); } await this.WriteToFileAsync(); } } } else { apiResult.Status = false; apiResult.HTTPStatus = (int)response.StatusCode; apiResult.Message = $"{apiResult.Message}"; } #endregion } else { APIResult fooAPIResult = JsonConvert.DeserializeObject <APIResult>(strResult, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore }); if (fooAPIResult != null) { apiResult = fooAPIResult; if (apiResult.Status == true) { apiResult.Status = false; apiResult.Message = strResult; } } else { apiResult.Status = false; apiResult.HTTPStatus = (int)response.StatusCode; apiResult.Message = string.Format("Error Code:{0}, Error Message:{1}", response.StatusCode, response.ReasonPhrase); } } } else { apiResult.Status = false; apiResult.Message = APIInternalError; } #endregion } catch (Exception ex) { apiResult.Status = false; apiResult.Message = ex.Message; } } return(apiResult); }