private static ApiRequestResultModel <T> CheckErrorMessage <T>(WebException ex, RequestResultTempModel parameter) { var resultModel = new ApiRequestResultModel <T> { Exception = ex, IsTimeoutException = ex.Status == WebExceptionStatus.Timeout }; if (ex.Response == null) { //如果有指定Log行為 parameter.ResponseStatusCode = (int)ex.Status; parameter.ResponseContent = string.Empty; ExecuteLogAction(parameter); resultModel.ResultObject = default(T); return(resultModel); } string errorMessage = string.Empty; using (var stream = ex.Response.GetResponseStream()) using (var reader = new StreamReader(stream)) { errorMessage = reader.ReadToEnd(); } //如果有指定Log行為 parameter.ResponseStatusCode = (int)ex.Status; parameter.ResponseContent = errorMessage; ExecuteLogAction(parameter); //若指定型別為string 特別處理 if (typeof(T) == typeof(string)) { resultModel.ResultObject = (T)(object)errorMessage; resultModel.ResponseText = errorMessage; return(resultModel); } resultModel.ResultObject = default(T); resultModel.ResponseText = errorMessage; return(resultModel); }
public static ApiRequestResultModel <T> RequestApiResult <T>(RequestParameters parameter, object postBodyModel = null) { //檢查與防呆 VerifyParameters(parameter); var requestParameterTemp = new RequestResultTempModel(); requestParameterTemp.RequestParameters = parameter; requestParameterTemp.RequestContent = string.Empty; requestParameterTemp.Timer = new Stopwatch(); requestParameterTemp.Timer.Start(); //new Instance HttpWebRequest httpWebRequest = InstanceHttpWebRequest(parameter); httpWebRequest.Timeout = parameter.TimeoutMillisecond; requestParameterTemp.HttpWebRequest = httpWebRequest; try { switch (parameter.Method) { case HttpMethodType.HttpDelete: case HttpMethodType.HttpGet: ApiRequestResultModel <T> resultModel = GetResponse <T>(httpWebRequest, requestParameterTemp); return(resultModel); break; } //HttpPOST HttpPut using (var streamWriter = InstanceStreamWrite(httpWebRequest, parameter.EncodingType)) { string jsonBody = string.Empty; //設定 POST json body if (postBodyModel == null) { jsonBody = SetJsonParameters(streamWriter, parameter); } else { jsonBody = SetJsonParametersByModel(streamWriter, postBodyModel); } requestParameterTemp.RequestContent = jsonBody; ApiRequestResultModel <T> resultModel = GetResponse <T>(httpWebRequest, requestParameterTemp); return(resultModel); } } catch (WebException ex) { return(CheckErrorMessage <T>(ex, requestParameterTemp)); } catch (System.Exception ex) { //如果有指定Log行為 requestParameterTemp.ResponseStatusCode = 500; requestParameterTemp.ResponseContent = ex.Message; ExecuteLogAction(requestParameterTemp); return(new ApiRequestResultModel <T> { Exception = ex }); } }
public static T RequestApi <T>(RequestParameters parameter, object postBodyModel = null) { ApiRequestResultModel <T> requestResult = RequestApiResult <T>(parameter, postBodyModel); return(requestResult.ResultObject); }