diff --git a/Unosquare.Labs.EmbedIO/Extensions.cs b/Unosquare.Labs.EmbedIO/Extensions.cs index 360cd8905..e3a0fb6d3 100644 --- a/Unosquare.Labs.EmbedIO/Extensions.cs +++ b/Unosquare.Labs.EmbedIO/Extensions.cs @@ -205,10 +205,11 @@ public static bool JsonResponse(this HttpListenerContext context, string json) context.Response.OutputStream.Write(buffer, 0, buffer.Length); return true; - } - + } + /// /// Parses the json as a given type from the request body. + /// Please note the underlying input stream is not rewindable. /// /// /// The context. @@ -216,12 +217,26 @@ public static bool JsonResponse(this HttpListenerContext context, string json) public static T ParseJson(this HttpListenerContext context) where T : class { - var body = context.RequestBody(); - return body == null ? null : JsonConvert.DeserializeObject(body); + var requestBody = context.RequestBody(); + return requestBody == null ? null : JsonConvert.DeserializeObject(requestBody); + } + + /// + /// Parses the json as a given type from the request body string. + /// + /// + /// The request body. + /// + public static T ParseJson(this string requestBody) + where T : class + { + return requestBody == null ? null : JsonConvert.DeserializeObject(requestBody); } /// - /// Retrieves the request body + /// Retrieves the request body as a string. + /// Note that once this method returns, the underlying input stream cannot be read again as + /// it is not rewindable for obvious reasons. This functionality is by design. /// /// The context. /// @@ -263,6 +278,7 @@ public static bool HasRequestHeader(this HttpListenerContext context, string hea /// /// Returns dictionary from Request POST data + /// Please note the underlying input stream is not rewindable. /// /// /// @@ -276,16 +292,35 @@ public static Dictionary RequestFormData(this HttpListenerContex using (var reader = new StreamReader(body, request.ContentEncoding)) { var stringData = reader.ReadToEnd(); - - if (string.IsNullOrWhiteSpace(stringData)) return null; - - return stringData.Split('&') - .ToDictionary(c => c.Split('=')[0], - c => WebUtility.UrlDecode(c.Split('=')[1])); + return ParseFormData(stringData); } } - } - + } + + /// + /// Returns dictionary from Request POST data + /// + /// The request body. + /// + public static Dictionary RequestFormData(this string requestBody) + { + return ParseFormData(requestBody); + } + + /// + /// Parses the form data given the request body string. + /// + /// The request body. + /// + private static Dictionary ParseFormData(string requestBody) + { + if (string.IsNullOrWhiteSpace(requestBody)) return null; + + return requestBody.Split('&') + .ToDictionary(c => c.Split('=')[0], + c => WebUtility.UrlDecode(c.Split('=')[1])); + } + /// /// Compresses the specified buffer using the G-Zip compression algorithm. ///