public static string ToMimeString(this KnownContentSerializers knownContentSerializer) { switch (knownContentSerializer) { case KnownContentSerializers.Json: return("application/json"); case KnownContentSerializers.Xml: return("application/xml"); default: return("application/octet-stream"); } }
public static async Task <HttpWebResponse> PostAsync(string url, object content = null, KnownContentSerializers accept = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json) { var req = WebRequest.CreateHttp(url); req.Method = HttpMethod.Post.ToString(); req.Accept = accept.ToMimeString(); req.ContentType = returnType.ToMimeString(); if (content == null) { req.ContentLength = 0; } else { var contentString = string.Empty; if (accept == KnownContentSerializers.Json) { contentString = JsonConvert.SerializeObject(content); } else if (accept == KnownContentSerializers.Xml) { var xmlSerializer = new XmlSerializer(content.GetType()); using (var sw = new StringWriter()) { xmlSerializer.Serialize(sw, content); contentString = sw.ToString(); } } else { //TODO:other type. } using (var stream = await req.GetRequestStreamAsync()) { using (var sw = new StreamWriter(stream)) { await sw.WriteAsync(contentString); } } } return((HttpWebResponse)await req.GetResponseAsync()); }
/// <summary> /// GETs a web request to an URL and returns the raw http web response /// </summary> /// <remarks>IMPORTANT: Remember to close the returned <see cref="HttpWebResponse"/> stream once done</remarks> /// <param name="url">The URL</param> /// <param name="configureRequest">Allows caller to customize and configure the request prior to the request being sent</param> /// <param name="bearerToken">If specified, provides the Authorization header with `bearer token-here` for things like JWT bearer tokens</param> /// <returns></returns> public static async Task <HttpWebResponse> GetAsync(string url, KnownContentSerializers returnType = KnownContentSerializers.Json, Action <HttpWebRequest> configureRequest = null, string bearerToken = null) { #region Setup // Create the web request var request = WebRequest.CreateHttp(url); // Make it a GET request method request.Method = HttpMethod.Get.ToString(); // Set the appropriate return type request.Accept = returnType.ToMimeString(); // If we have a bearer token... if (bearerToken != null) { // Add bearer token to header request.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {bearerToken}"); } // Any custom work configureRequest?.Invoke(request); #endregion // Wrap call... try { // Return the raw server response return(await request.GetResponseAsync() as HttpWebResponse); } // Catch Web Exceptions (which throw for things like 401) catch (WebException ex) { // If we got a response... if (ex.Response is HttpWebResponse httpResponse) { // Return the response return(httpResponse); } // Otherwise, we don't have any information to be able to return // So re-throw throw; } }
/// <summary> /// Takes a known serializer type and returns the Mime type associated with it /// </summary> /// <param name="serializer">The serializer</param> /// <returns></returns> public static string ToMimeString(this KnownContentSerializers serializer) { // Switch on the serializer switch (serializer) { // Json case KnownContentSerializers.Json: return("application/json"); // XML case KnownContentSerializers.Xml: return("application/xml"); // Unknown default: return("application/octet-stream"); } }
public static HttpWebResponse Post(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json) { var request = WebRequest.CreateHttp(url); request.Method = HttpMethod.Post.ToString(); request.Accept = returnType.ToMimeString(); request.ContentType = sendType.ToMimeString(); var contentString = string.Empty; if (content == null) { request.ContentLength = 0; } else { if (sendType == KnownContentSerializers.Xml) { var xmlSerializer = new XmlSerializer(content.GetType()); using (var stringWriter = new StringWriter()) { xmlSerializer.Serialize(stringWriter, content); contentString = stringWriter.ToString(); } } else if (sendType == KnownContentSerializers.Json) { contentString = JsonConvert.SerializeObject(content); } } using (var requestString = request.GetRequestStream()) { using (var streamWriter = new StreamWriter(requestString)) { streamWriter.Write(contentString); } } return(request.GetResponse() as HttpWebResponse); }
/// <summary> /// Posts a web request to an URL and returns the raw http web response /// </summary> /// <param name="url">The URL to post to</param> /// <param name="content">The content to post</param> /// <param name="sendType">The format to serialize the content into</param> /// <param name="returnType">The expected type of content to be returned from the server</param> /// <param name="configureRequest">Allows caller to customize and configure the request prior to the content being written and sent</param> /// <param name="bearerToken">If specified, provides the Authorization header with `bearer token-here` for things like JWT bearer tokens</param> /// <returns></returns> public static async Task <HttpWebResponse> PostAsync(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json, Action <HttpWebRequest> configureRequest = null, string bearerToken = null) { #region Setup // Create the web request var request = WebRequest.CreateHttp(url); // Make it a POST request method request.Method = HttpMethod.Post.ToString(); // Set the appropriate return type request.Accept = returnType.ToMimeString(); // Set the content type request.ContentType = sendType.ToMimeString(); // If we have a bearer token... if (bearerToken != null) { // Add bearer token to header request.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {bearerToken}"); } // Any custom work configureRequest?.Invoke(request); #endregion #region Write Content // Set the content length if (content == null) { // Set content length to 0 request.ContentLength = 0; } // Otherwise... else { // Create content to write var contentString = string.Empty; // Serialize to Json? if (sendType == KnownContentSerializers.Json) { // Serialize content to Json string contentString = JsonConvert.SerializeObject(content); } // Serialize to Xml? else if (sendType == KnownContentSerializers.Xml) { // Create Xml serializer var xmlSerializer = new XmlSerializer(content.GetType()); // Create a string writer to receive the serialized string using (var stringWriter = new StringWriter()) { // Serialize the object to a string xmlSerializer.Serialize(stringWriter, content); // Extract the string from the writer contentString = stringWriter.ToString(); } } // Currently unknown else { // TODO: Throw error once we have Dna Framework exception types } // Get body stream... using (var requestStream = await request.GetRequestStreamAsync()) // Create a stream writer from the body stream... using (var streamWriter = new StreamWriter(requestStream)) // Write content to HTTP body stream await streamWriter.WriteAsync(contentString); } #endregion // Wrap call... try { // Return the raw server response return(await request.GetResponseAsync() as HttpWebResponse); } // Catch Web Exceptions (which throw for things like 401) catch (WebException ex) { // And instead, return the response and let the caller decide what to do with the StatusCode return(ex.Response as HttpWebResponse); } }
/// <summary> /// Posts a web request to an URL and returns a response of the expected data type /// </summary> /// <param name="url">The URL to post to</param> /// <param name="content">The content to post</param> /// <param name="sendType">The format to serialize the content into</param> /// <param name="returnType">The expected type of content to be returned from the server</param> /// <param name="configureRequest">Allows caller to customize and configure the request prior to the content being written and sent</param> /// <param name="bearerToken">If specified, provides the Authorization header with `bearer token-here` for things like JWT bearer tokens</param> /// <returns></returns> public static async Task <WebRequestResult <TResponse> > PostAsync <TResponse>(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json, Action <HttpWebRequest> configureRequest = null, string bearerToken = null) { // Make the standard Post call first var serverResponse = await PostAsync(url, content, sendType, returnType, configureRequest, bearerToken); // Create a result var result = serverResponse.CreateWebRequestResult <TResponse>(); // If the response status code is not 200... if (result.StatusCode != HttpStatusCode.OK) { // Call failed // Return no error message so the client can display its own based on the status code // Done return(result); } // If we have no content to deserialize... if (result.RawServerResponse.IsNullOrEmpty()) { // Done return(result); } // Deserialize raw response try { // If the server response type was not the expected type... if (!serverResponse.ContentType.ToLower().Contains(returnType.ToMimeString().ToLower())) { // Fail due to unexpected return type result.ErrorMessage = $"Server did not return data in expected type. Expected {returnType.ToMimeString()}, received {serverResponse.ContentType}"; // Done return(result); } // Json? if (returnType == KnownContentSerializers.Json) { // Deserialize Json string result.ServerResponse = JsonConvert.DeserializeObject <TResponse>(result.RawServerResponse); } // Xml? else if (returnType == KnownContentSerializers.Xml) { // Create Xml serializer var xmlSerializer = new XmlSerializer(typeof(TResponse)); // Create a memory stream for the raw string data using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(result.RawServerResponse))) // Deserialize XML string result.ServerResponse = (TResponse)xmlSerializer.Deserialize(memoryStream); } // Unknown else { // If deserialize failed then set error message result.ErrorMessage = "Unknown return type, cannot deserialize server response to the expected type"; // Done return(result); } } catch (Exception ex) { // If deserialize failed then set error message result.ErrorMessage = "Failed to deserialize server response to the expected type"; // Done return(result); } // Return result return(result); }
/// <summary> /// Posts a web requests to an URL and return the raw http web response /// </summary> /// <param name="url">The URL to post to</param> /// <param name="content">The content to post</param> /// <param name="sendType">The format to serialize the content into</param> /// <param name="returnType">The expected type of content to be returned from the server</param> /// <returns></returns> public static async Task <HttpWebResponse> PostAsync(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json, Action <HttpWebRequest> configureRequest = null, string bearerToken = null) { // create the web request var request = WebRequest.CreateHttp(url); request.Method = HttpMethod.Post.ToString(); request.Accept = returnType.ToMimeString(); request.ContentType = sendType.ToMimeString(); if (bearerToken != null) { // Add bearer token to header request.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {bearerToken}"); } // Any custom work configureRequest?.Invoke(request); if (content == null) { request.ContentLength = 0; } else { var contentString = string.Empty; if (sendType == KnownContentSerializers.Json) { contentString = JsonConvert.SerializeObject(content); } else if (sendType == KnownContentSerializers.Xml) { var xmlSerializer = new XmlSerializer(content.GetType()); using (var stringWriter = new StringWriter()) { xmlSerializer.Serialize(stringWriter, content); contentString = stringWriter.ToString(); } } else { // TODO: Throw error } using (var requestStream = await request.GetRequestStreamAsync()) using (var streamWriter = new StreamWriter(requestStream)) await streamWriter.WriteAsync(contentString); } try { var response = await request.GetResponseAsync(); return(await request.GetResponseAsync() as HttpWebResponse); } catch (WebException ex) { if (ex.Response is HttpWebResponse httpResponse) { return(httpResponse); } throw; } }
/// <summary> /// Posts a web requests to an URL and return a response of the expected data type /// </summary> /// <param name="url">The URL to post to</param> /// <param name="content">The content to post</param> /// <param name="sendType">The format to serialize the content into</param> /// <param name="returnType">The expected type of content to be returned from the server</param> /// <returns></returns> public static async Task <WebRequestResult <TResponse> > PostAsync <TResponse>(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json) { //standart post call var serverResponse = await PostAsync(url, content, sendType, returnType); var result = serverResponse.CreateWebRequstResult <TResponse>(); if (result.StatusCode != HttpStatusCode.OK) { // TODO: locolize string result.ErrorMessage = $"Server returned unsuccessfull status code. {serverResponse.StatusCode} {serverResponse.StatusDescription}"; return(result); } if (string.IsNullOrWhiteSpace(result.RawServerResponse)) { return(result); } try { if (!serverResponse.ContentType.ToLower().Contains(KnownContentSerializers.Json.ToMimeString().ToLower())) { result.ErrorMessage = $"Uknown return type. Expected {returnType.ToMimeString()}, received {serverResponse.ContentType.ToLower()}"; return(result); } if (returnType == KnownContentSerializers.Json) { result.ServerResponse = JsonConvert.DeserializeObject <TResponse>(result.RawServerResponse); } else if (returnType == KnownContentSerializers.Xml) { var xmlSerializer = new XmlSerializer(typeof(TResponse)); using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(result.RawServerResponse))) { result.ServerResponse = (TResponse)xmlSerializer.Deserialize(memoryStream); } } else { result.ErrorMessage = "Uknown return type"; return(result); } } catch (Exception ex) { result.ErrorMessage = $"Failed to deserialize server response. Error {ex.Message}"; return(result); } return(result); }
/// <summary> /// POSTs a web request to an URL and returns the raw http web response /// </summary> /// <remarks>IMPORTANT: Remember to close the returned <see cref="HttpWebResponse"/> stream once done</remarks> /// <param name="url">The URL</param> /// <param name="content">The content to post</param> /// <param name="sendType">The format to serialize the content into</param> /// <param name="returnType">The expected type of content to be returned from the server</param> /// <param name="configureRequest">Allows caller to customize and configure the request prior to the content being written and sent</param> /// <param name="bearerToken">If specified, provides the Authorization header with `bearer token-here` for things like JWT bearer tokens</param> /// <returns></returns> public static async Task <HttpWebResponse> PostAsync(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json, Action <HttpWebRequest> configureRequest = null, string bearerToken = null) { #region Setup // Create the web request var request = WebRequest.CreateHttp(url); // Make it a POST request method request.Method = HttpMethod.Post.ToString(); // Set the appropriate return type request.Accept = returnType.ToMimeString(); // Set the content type request.ContentType = sendType.ToMimeString(); // If we have a bearer token... if (bearerToken != null) { // Add bearer token to header request.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {bearerToken}"); } // Any custom work configureRequest?.Invoke(request); #endregion #region Write Content // Set the content length if (content == null) { // Set content length to 0 request.ContentLength = 0; } // Otherwise... else { // Create content to write var contentString = string.Empty; // Serialize to Json? if (sendType == KnownContentSerializers.Json) { // Serialize content to Json string contentString = JsonConvert.SerializeObject(content); } // Serialize to Xml? else if (sendType == KnownContentSerializers.Xml) { // Create Xml serializer var xmlSerializer = new XmlSerializer(content.GetType()); // Create a string writer to receive the serialized string using (var stringWriter = new StringWriter()) { // Serialize the object to a string xmlSerializer.Serialize(stringWriter, content); // Extract the string from the writer contentString = stringWriter.ToString(); } } // Currently unknown else { // TODO: Throw error once we have DNA Framework exception types } // // NOTE: This GetRequestStreamAsync could throw with a // SocketException (or an inner exception of SocketException) // // However, we cannot return anything useful from this // so we just let it throw out so the caller can handle // this (the other PostAsync call for example). // // SocketExceptions are a good indication there is no // Internet, or no connection or firewalls blocking // communication. // // Get body stream... using (var requestStream = await request.GetRequestStreamAsync()) // Create a stream writer from the body stream... using (var streamWriter = new StreamWriter(requestStream)) // Write content to HTTP body stream await streamWriter.WriteAsync(contentString); } #endregion // Wrap call... try { // Return the raw server response return(await request.GetResponseAsync() as HttpWebResponse); } // Catch Web Exceptions (which throw for things like 401) catch (WebException ex) { // If we got a response... if (ex.Response is HttpWebResponse httpResponse) { // Return the response return(httpResponse); } // Otherwise, we don't have any information to be able to return // So re-throw throw; } }
/// <summary> /// Posts a web request to an URL and returns the raw http web response /// </summary> /// <param name="url">The URL to post to</param> /// <param name="content">The content to post</param> /// <param name="sendType">The format to serialize the content into</param> /// <param name="returnType">The expected type of content to be returned from the server</param> /// <returns></returns> public static async Task <HttpWebResponse> PostAsync(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json) { #region Setup // Create the web request var request = WebRequest.CreateHttp(url); // Make it a POST request method request.Method = HttpMethod.Post.ToString(); // Set the appropriate return type request.Accept = returnType.ToMimeString(); // Set the content type request.ContentType = sendType.ToMimeString(); #endregion #region Write Content // Set the content length if (content == null) { // Set content length to 0 request.ContentLength = 0; } // Otherwise... else { // Create content to write var contentString = string.Empty; // Serialize to Json? if (sendType == KnownContentSerializers.Json) { // Serialize content to Json string contentString = JsonConvert.SerializeObject(content); } // Serialize to Xml? else if (sendType == KnownContentSerializers.Xml) { // Create Xml serializer var xmlSerializer = new XmlSerializer(content.GetType()); // Create a string writer to receive the serialized string using (var stringWriter = new StringWriter()) { // Serialize the object to a string xmlSerializer.Serialize(stringWriter, content); // Extract the string from the writer contentString = stringWriter.ToString(); } } // Currently unknown else { // TODO: Throw error once we have Dna Framework exception types } // Get body stream... using (var requestStream = await request.GetRequestStreamAsync()) // Create a stream writer from the body stream... using (var streamWriter = new StreamWriter(requestStream)) // Write content to HTTP body stream await streamWriter.WriteAsync(contentString); } #endregion // Return the raw server response return(await request.GetResponseAsync() as HttpWebResponse); }
public static WebRequestResult <TResponse> Post <TResponse>(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json) { var serverResposne = Post(url, content, sendType, returnType); var result = serverResposne.CreateWebRequestResult <TResponse>(); if (result.StatusCode != HttpStatusCode.OK) { result.ErrorMessage = $"Server returned unsuccesful status code. {serverResposne.StatusCode} {serverResposne.StatusDescription}"; return(result); } if (result.RawServerResponse.IsNullOrEmpty()) { return(result); } try { if (!serverResposne.ContentType.ToLower().Contains(returnType.ToMimeString().ToLower())) { result.ErrorMessage = $"Server did not return data in expected type. Expected {returnType.ToMimeString()}, returned {serverResposne.ContentType}"; return(result); } if (returnType == KnownContentSerializers.Json) { result.ServerResponse = JsonConvert.DeserializeObject <TResponse>(result.RawServerResponse); } else if (returnType == KnownContentSerializers.Xml) { var xmlSerializer = new XmlSerializer(typeof(TResponse)); using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(result.RawServerResponse))) { result.ServerResponse = (TResponse)xmlSerializer.Deserialize(memoryStream); } } else { result.ErrorMessage = "Unknown return type, cannot deserialize to the expected type"; return(result); } } catch (Exception ex) { result.ErrorMessage = "Failed to deseserialize server response to the expected type"; return(result); } return(result); }
/// <summary> /// Posts a web request to and URL and returns the raw http web request /// </summary> /// <param name="url">The URL to post to</param> /// <param name="content">The content to post</param> /// <param name="sendType">The format to serialize the content into</param> /// <param name="returnType">The expected type of content to be returned from the server</param> /// <param name="configureRequest">Allows caller to customize and configure the request prior to the request being sent</param> /// <param name="bearerToken">If specified, provides the Authorization header with `bearer token-here` for things like JWT bearer tokens</param> /// <returns></returns> public static async Task <HttpWebResponse> PostAsync( string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json, Action <HttpWebRequest> configureRequest = null, string bearerToken = null) { #region Setup // Create the web request var request = WebRequest.CreateHttp(url); // Make it a POST request method request.Method = HttpMethod.Post.ToString(); // Set the appropriate return type request.Accept = returnType.ToMimeString(); // Set content type request.ContentType = sendType.ToMimeString(); // If we have a bearer token... if (bearerToken != null) { // Add bearer token to header request.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {bearerToken}"); } // Check if there is any custom request configureRequest?.Invoke(request); #endregion #region Write Content // Set content length if (content == null) { request.ContentLength = 0; } // Otherwise... else { // Create content to write var contentString = string.Empty; // Serialize to Json? if (sendType == KnownContentSerializers.Json) { // Serialize content to Json string contentString = JsonConvert.SerializeObject(content); } // Serialize to Xml? else if (sendType == KnownContentSerializers.Xml) { // Create xml serializer var xmlSerializer = new XmlSerializer(content.GetType()); // Create a string writer to receive the serialized string using (var stringWriter = new Utf8StringWriter()) { // Serialize the object to a string xmlSerializer.Serialize(stringWriter, content); // Extract the string from the writer contentString = stringWriter.ToString(); } } // Currently unknown else { //TODO: Throw error once we have ProjectUniversal Framework exception types } // Get the request stream(body stream) async... using (var requestStream = await request.GetRequestStreamAsync()) { // Create a stream writer to write to the body stream... using (var streamWriter = new StreamWriter(requestStream)) { // Write content to Http body stream await streamWriter.WriteAsync(contentString); } } } #endregion try { // Return the raw server response return(await request.GetResponseAsync() as HttpWebResponse); } catch (WebException ex) { // If we got a response... if (ex.Response is HttpWebResponse httpResponse) { // Return the response return(httpResponse); } // Otherwise, we don't have any information to be able to return // So re-throw throw; } }
/// <summary> /// Posts a web request to an URL and returns of the expected data type /// </summary> /// <param name="url">The URL to post to</param> /// <param name="content">The content to post</param> /// <param name="sendType">The format to serialize the content into</param> /// <param name="returnType">The expected type of content to be returned from the server</param> /// <param name="configureRequest">Allows caller to customize and configure the request prior to the request being sent</param> /// <param name="bearerToken">If specified, provides the Authorization header with `bearer token-here` for things like JWT bearer tokens</param> /// <returns></returns> public static async Task <WebRequestResult <TResponse> > PostAsync <TResponse>( string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json, Action <HttpWebRequest> configureRequest = null, string bearerToken = null) { // Create server response holder var serverResponse = default(HttpWebResponse); try { // Make standard Post call first serverResponse = await PostAsync(url, content, sendType, returnType, configureRequest, bearerToken); } catch (Exception ex) { // If we got unexpected error, return that return(new WebRequestResult <TResponse> { // Include exception message ErrorMessage = ex.Message }); } // Create a result var result = serverResponse.CreateWebRequestResult <TResponse>(); // If the response status code isn't equal to 200... if (result.StatusCode != HttpStatusCode.OK) { // Call failed // TODO: Localize string result.ErrorMessage = $"Server returned unsuccessful status code, { result.StatusCode } { result.StatusDescription }"; // Done return(result); } // If we have no content to deserialize if (result.RawServerResponse.IsNullOrEmpty()) { // Done return(result); } try { // If the server response type was not the expected type... if (!serverResponse.ContentType.ToLower().Contains(returnType.ToMimeString().ToLower())) { // Failed due to unexpected return type result.ErrorMessage = $"Server did not return data in expected type.Expected { returnType.ToMimeString() }, receiver { serverResponse.ContentType }"; // Done return(result); } // Deserialize to Json? if (returnType == KnownContentSerializers.Json) { // Deserialize json string result.ServerResponse = JsonConvert.DeserializeObject <TResponse>(result.RawServerResponse); } // Deserialize to Xml? else if (returnType == KnownContentSerializers.Xml) { // Create xml serializer var xmlSerializer = new XmlSerializer(typeof(TResponse)); // Create a memory stream for the raw string data using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(result.RawServerResponse))) { // Deserialize XML string result.ServerResponse = (TResponse)xmlSerializer.Deserialize(memoryStream); } } // Currently unknown else { result.ErrorMessage = "Unknown return type, cannot deserialize server response to the expected type"; // Done return(result); } } catch (Exception ex) { // If deserialize failed result.ErrorMessage = "Failed to deserialize server response to the expected type"; // Done return(result); } // Deserialize raw response return(result); }
/// <summary> /// Posts a web request to the server asynchronously /// </summary> /// <param name="url">URL where to post at</param> /// <param name="content">Data to post</param> /// <param name="sendType">The format to serialize the content to</param> /// <param name="returnType">The expected format of content to be returned from the server</param> /// <returns></returns> public static async Task <HttpWebResponse> PostAsync(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json, Action <HttpWebRequest> configureRequest = null, string bearerToken = null) { #region Setup Headers //Create a request var request = WebRequest.CreateHttp(url); //Make it s POST request type request.Method = HttpMethod.Post.ToString(); //Set the appropriate return type request.Accept = returnType.ToMimeString(); //Set the content type request.ContentType = sendType.ToMimeString(); //Set up token, if any if (bearerToken != null) { request.Headers.Add("Authorization", $"Bearer {bearerToken}"); } #endregion #region Configure HttpWebRequest //Add custom configuration to Request object configureRequest?.Invoke(request); #endregion #region Write Content //Set the content length if (content == null) { request.ContentLength = 0; } else { var contentString = string.Empty; if (sendType == KnownContentSerializers.Json) { //Convert to JSON format contentString = JsonConvert.SerializeObject(content); } else if (sendType == KnownContentSerializers.Xml) { //Convert to XML format var xmlSerializer = new XmlSerializer(content.GetType()); using (var stringWriter = new StringWriterUTF8()) { xmlSerializer.Serialize(stringWriter, content); contentString = stringWriter.ToString(); } } else { //TODO: Throw error once we have Dna.Framework exception types } //set the content length request.ContentLength = contentString.Length; //Get the request stream and write to it using (var requestStream = await request.GetRequestStreamAsync()) { using (var streamWriter = new StreamWriter(requestStream)) { await streamWriter.WriteAsync(contentString); } } } #endregion return(await request.GetResponseAsync() as HttpWebResponse); }
/// <summary> /// Posts a web request to the server asynchronously and returns with the of the expected data type /// </summary> /// <param name="url">URL where to post at</param> /// <param name="content">Data to post</param> /// <param name="sendType">The format to serialize the content to</param> /// <param name="returnType">The expected format of content to be returned from the server</param> /// <returns></returns> public static async Task <WebRequestResult <TResponse> > PostAsync <TResponse>(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json, Action <HttpWebRequest> configureRequest = null, string bearerToken = null) { //Make the standard POST call first var serverResponse = await PostAsync(url, content, sendType, returnType, configureRequest, bearerToken); //Create a result var result = serverResponse.CreateWebRequestResult <TResponse>(); //If the response is not 200 OK if (result.StatusCode != HttpStatusCode.OK) { //TODO: Localize strings result.ErrorMessage = $"Server returned unsuccessful status code {result.StatusCode} => {result.StatusDescription}"; return(result); } //Deserialize Raw Response if (result.RawServerResponse.IsNulOrEmpty()) { return(result); } //Deserialize raw response try { if (!serverResponse.ContentType.ToLower().Contains(returnType.ToMimeString().ToLower())) { result.ErrorMessage = $"Server did not return data in expected format. Expected {returnType.ToMimeString()}, received {serverResponse.ContentType}"; return(result); } if (returnType == KnownContentSerializers.Json) { result.ServerResponse = JsonConvert.DeserializeObject <TResponse>(result.RawServerResponse); } else if (returnType == KnownContentSerializers.Xml) { //Convert to XML format var xmlSerializer = new XmlSerializer(typeof(TResponse)); using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(result.RawServerResponse))) { result.ServerResponse = (TResponse)xmlSerializer.Deserialize(memoryStream); } } else { result.ErrorMessage = "Unknown return type, cannot deserialize server response to the expected type"; return(result); } } catch (Exception ex) { result.ErrorMessage = $"Failed to deserialize server response => {ex.Message}"; return(result); } return(result); }