diff --git a/src/Spoleto.Common/Helpers/HttpHelper.cs b/src/Spoleto.Common/Helpers/HttpHelper.cs new file mode 100644 index 0000000..3bef25b --- /dev/null +++ b/src/Spoleto.Common/Helpers/HttpHelper.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Unicode; +using System.Threading.Tasks; +using System.Web; + +namespace Spoleto.Common.Helpers +{ + /// + /// The HTTP helper. + /// + public static class HttpHelper + { + /// + /// Converts the given object to HTTP query string. + /// + public static string ToQueryString(T body) + { + var bodyJson = JsonHelper.ToJson(body); + var dictionaryAsObjectValues = JsonHelper.FromJson>(bodyJson); + + var args = new List(); + foreach (var key in dictionaryAsObjectValues.Keys) + { + var jsonValue = (JsonElement)dictionaryAsObjectValues[key]; + var objValue = FlattenJsonValue(jsonValue); + if (objValue is string str) + { + args.Add($"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(str)}"); + } + else if (objValue is IEnumerable enumerable) + { + foreach (string item in enumerable) + { + args.Add($"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(item)}"); + } + } + } + + return string.Join("&", args); + } + + private static object FlattenJsonValue(JsonElement objValue) + { + return objValue.ValueKind switch + { + JsonValueKind.String => objValue.GetString(), + JsonValueKind.Array => objValue.EnumerateArray().Select(FlattenJsonValue), + _ => objValue.GetRawText() + }; + } + } +} diff --git a/src/Spoleto.Common/Helpers/JsonHelper.cs b/src/Spoleto.Common/Helpers/JsonHelper.cs index fae6ed1..0b97aca 100644 --- a/src/Spoleto.Common/Helpers/JsonHelper.cs +++ b/src/Spoleto.Common/Helpers/JsonHelper.cs @@ -103,44 +103,5 @@ public static async Task FromJsonStreamAsync(Stream jsonStream) return body; } - - /// - /// Converts to a query string. - /// - public static string ToQueryString(T body) - { - var bodyJson = ToJson(body); - var dictionaryAsObjectValues = FromJson>(bodyJson); - - var args = new List(); - foreach (var key in dictionaryAsObjectValues.Keys) - { - var jsonValue = (JsonElement)dictionaryAsObjectValues[key]; - var objValue = FlattenJsonValue(jsonValue); - if (objValue is string str) - { - args.Add($"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(str)}"); - } - else if (objValue is IEnumerable enumerable) - { - foreach (string item in enumerable) - { - args.Add($"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(item)}"); - } - } - } - - return string.Join("&", args); - } - - private static object FlattenJsonValue(JsonElement objValue) - { - return objValue.ValueKind switch - { - JsonValueKind.String => objValue.GetString(), - JsonValueKind.Array => objValue.EnumerateArray().Select(FlattenJsonValue), - _ => objValue.GetRawText() - }; - } } }