protected async Task <IRestResponse> MakeRequestAsync(string endPoint, RestSharp.Method method, Dictionary <string, string> headers = null, Dictionary <string, string> bodyParameters = null, object dataBody = null, String filePath = null) { var client = new RestClient(BASE_URL); var request = new RestRequest(endPoint, method); // ToDo: create method overrides if (headers != null) { foreach (KeyValuePair <string, string> item in headers) { request.AddHeader(item.Key, item.Value); } } if (bodyParameters != null) { foreach (KeyValuePair <string, string> item in bodyParameters) { request.AddParameter(item.Key, item.Value); } } if (!string.IsNullOrWhiteSpace(filePath)) { request.AddHeader("Content-Type", MimeType(filePath)); request.AddHeader("Content-Disposition", string.Format("file; filename=\"{0}\"", Path.GetFileNameWithoutExtension(filePath))); request.AddParameter(MimeType(filePath), File.ReadAllBytes(filePath), ParameterType.RequestBody); //request.AddFile(Path.GetFileNameWithoutExtension(filePath), filePath); //request.AlwaysMultipartFormData = false; //request.AddHeader("Content-Type", MimeType(filePath)); } if (dataBody != null) { // the request.AddJsonBody() override the Content-Type header to RestSharp... this is a workaround request.AddParameter(headers["Content-Type"], JsonConvert.SerializeObject(dataBody), ParameterType.RequestBody); } IRestResponse response = await client.ExecuteTaskAsync(request); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { OnUnauthorized?.Invoke(this, new StatusCodeEventArgs(endPoint)); return(null); } return(response); }
private R ExecuteHandlers <R>(R restResponse) where R : IAPIRestResponse { var eventContext = new APIResponseEventContext(restResponse); switch (restResponse.StatusCode) { case HttpStatusCode.NotFound: case HttpStatusCode.BadRequest: { OnBadRequest?.Invoke(eventContext); break; } case HttpStatusCode.Unauthorized: { OnUnauthorized?.Invoke(eventContext); break; } default: { throw new Exception("Unexpected Case"); } } if (!eventContext.EventHandled) { ThrowHttpException(restResponse); } if (eventContext.RetryLastRequest) { var methods = GetType().GetMethods().Where(s => s.Name == "ExecuteAsync"); var method = methods.FirstOrDefault(); if (eventContext.RestResponse.GetType().IsGenericType) { method = methods.LastOrDefault().MakeGenericMethod(eventContext.RestResponse.GetType().GenericTypeArguments); } eventContext.RestResponse = ((Task <R>)method.Invoke(this, new object[] { eventContext.RestResponse.Request })).Result; } return((R)eventContext.RestResponse); }