/// <summary> /// Executes a GET on the given HttpClient /// </summary> /// <typeparam name="OutType">Return type of the GET response body</typeparam> /// <param name="controller">API controller name</param> /// <param name="uriFormat">Format of the Uri parameters</param> /// <param name="values">Values used to create Uri parameters</param> /// <returns>Results</returns> public HttpResults <OutType> Get <OutType>(string controller, SerializationModesEnum json, string uriFormat, params object[] values) { HttpResults <OutType> result = new HttpResults <OutType>(HttpStatusCode.NotFound, null); HttpClient client = GetClient(); try { string controllerUriFmt = string.IsNullOrEmpty(controller) ? uriFormat : controller + "/" + uriFormat; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format(controllerUriFmt, values)); AddAcceptHeaders(request, SerializationMode); HttpResponseMessage response = client.SendAsync(request).Result; result = ParseResponse <OutType>(response); } catch (Exception ex) { System.Reflection.MethodBase mb = System.Reflection.MethodBase.GetCurrentMethod(); System.Diagnostics.Debug.WriteLine(ex.Message, string.Format("{0}.{1}.{2}", mb.DeclaringType.Namespace, mb.DeclaringType.Name, mb.Name)); } return(result); }
/// <summary> /// Executes an HTTP method on the given Url /// </summary> /// <typeparam name="InType">Type of data to be sent in the request</typeparam> /// <typeparam name="OutType">Output type to be parsed from the response</typeparam> /// <param name="method">Method to execute</param> /// <param name="controller">API controller name</param> /// <param name="input">Data to send with the request</param> /// <param name="uriFormat">Format of the Uri parameters</param> /// <param name="values">Values used to create Uri parameters</param> /// <returns>Http results class object that contains either the result data or error</returns> public HttpResults <OutType> ExecuteHttpMethod <InType, OutType>(HttpMethod method, string controller, InType input, string uriFormat, params object[] values) { HttpResults <OutType> result = null; string contentString = null; try { // Get client reference HttpClient client = GetClient(); HttpContent content = null; string controllerUriFmt = string.IsNullOrEmpty(controller) ? uriFormat : controller + "/" + uriFormat; // Get appropriate serializer switch (SerializationMode) { case SerializationModesEnum.Json: JsonSerializerSettings settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; contentString = JsonConvert.SerializeObject(input, settings); break; case SerializationModesEnum.Xml: default: XmlObjectSerializer serializer = new DataContractSerializer(typeof(InType)); // Build body content using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, input); contentString = UTF8Encoding.UTF8.GetString(ms.ToArray()); } break; } content = new StringContent(contentString, Encoding.UTF8, GetContentMediaTypeName(SerializationMode)); // Execute call string uri = ""; if (!string.IsNullOrEmpty(controllerUriFmt)) { uri = string.Format(controllerUriFmt, values); } using (HttpRequestMessage request = new HttpRequestMessage(method, uri)) { AddAcceptHeaders(request, SerializationMode); request.Content = content; using (HttpResponseMessage response = client.SendAsync(request).Result) { result = ParseResponse <OutType>(response); } } } catch (Exception ex) { System.Reflection.MethodBase mb = System.Reflection.MethodBase.GetCurrentMethod(); System.Diagnostics.Debug.WriteLine(ex.Message, string.Format("{0}.{1}.{2}", mb.DeclaringType.Namespace, mb.DeclaringType.Name, mb.Name)); } return(result); }
/// <summary> /// Parses an HttpResponseMessage for a single output item /// </summary> /// <typeparam name="OutType">Type of object embedded in the body</typeparam> /// <param name="response">Http Response to parse</param> /// <returns>Parsed data</returns> private HttpResults <OutType> ParseResponse <OutType>(HttpResponseMessage response) { HttpResults <OutType> result = new HttpResults <OutType>(HttpStatusCode.NotFound, default(OutType)); Stream stream = null; string contents = null; if ((response != null) && (response.Content != null) && (response.Content.Headers != null) && (response.Content.Headers.Count() > 0)) { stream = response.Content.ReadAsStreamAsync().Result; contents = stream.StreamToString(); result.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) { // Try to parse results into OutputType try { switch (response.Content.Headers.ContentType.MediaType) { case Consts.CONTENT_JSON: result.Result = JsonConvert.DeserializeObject <OutType>(contents, JsonSettings); break; case Consts.CONTENT_XML: default: DataContractSerializer serializer = new DataContractSerializer(typeof(OutType)); result.Result = (OutType)serializer.ReadObject(stream); break; } } catch (Exception ex) { // Error trying to parse the results System.Reflection.MethodBase mb = System.Reflection.MethodBase.GetCurrentMethod(); System.Diagnostics.Trace.WriteLine(ex.Message, string.Format("{0}.{1}.{2}", mb.DeclaringType.Namespace, mb.DeclaringType.Name, mb.Name)); result.StatusCode = HttpStatusCode.BadRequest; result.Error = string.Format("{0}: {1}", ex.Message, contents); } } else { // Non-success status code, try to parse response contents into a string for the error message try { switch (response.Content.Headers.ContentType.MediaType) { case Consts.CONTENT_JSON: result.Error = JsonConvert.DeserializeObject <string>(contents, JsonSettings); break; case Consts.CONTENT_XML: default: DataContractSerializer serializer = new DataContractSerializer(typeof(string)); result.Error = (string)serializer.ReadObject(stream); break; } } catch (Exception ex) { // Error trying to parse the results System.Reflection.MethodBase mb = System.Reflection.MethodBase.GetCurrentMethod(); System.Diagnostics.Trace.WriteLine(ex.Message, string.Format("{0}.{1}.{2}", mb.DeclaringType.Namespace, mb.DeclaringType.Name, mb.Name)); result.Error = string.Format("{0}: {1}", ex.Message, contents); } } } return(result); }