HttpClientRequestExtensions.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Web;
  8. namespace EasyDevCore.Remote.HttpAccess
  9. {
  10. /// <summary>
  11. ///
  12. /// </summary>
  13. public static class HttpClientRequestExtensions
  14. {
  15. /// <summary>
  16. /// set the base URL.
  17. /// </summary>
  18. /// <param name="httpClient">The HTTP client.</param>
  19. /// <param name="baseUrl">The base URL.</param>
  20. /// <returns></returns>
  21. public static HttpClient BaseUrl(this HttpClient httpClient, string baseUrl)
  22. {
  23. httpClient.BaseAddress = new Uri(baseUrl);
  24. return httpClient;
  25. }
  26. /// <summary>
  27. /// Posts as parameter asynchronous.
  28. /// </summary>
  29. /// <typeparam name="T"></typeparam>
  30. /// <param name="httpClient">The HTTP client.</param>
  31. /// <param name="url">The URL.</param>
  32. /// <param name="data">The data.</param>
  33. /// <param name="cancellationToken">The cancellation token.</param>
  34. /// <returns></returns>
  35. public static async Task<HttpResponseMessage> PostAsParamAsync<T>(this HttpClient httpClient, string url, T data, CancellationToken cancellationToken = default)
  36. {
  37. if (typeof(T).IsArray)
  38. {
  39. StringBuilder sb = new StringBuilder(url);
  40. foreach (var item in data as object[])
  41. {
  42. sb.Append("/" + HttpUtility.UrlEncode(item.ToInvariantString()));
  43. }
  44. return await httpClient.PostAsync(sb.ToString(), (HttpContent)null, cancellationToken).ConfigureAwait(false);
  45. }
  46. else
  47. {
  48. var argValues = data.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
  49. .ToDictionary(p => p.Name, p => p.GetValue(data).ToInvariantString());
  50. var formContent = new FormUrlEncodedContent(argValues); //HttpAccessSetup.UrlEncodedSerializerRequest.Serialize(argValues);
  51. return await httpClient.PostAsync(url, formContent, cancellationToken).ConfigureAwait(false);
  52. }
  53. }
  54. /// <summary>
  55. /// Gets the asynchronous.
  56. /// </summary>
  57. /// <typeparam name="T"></typeparam>
  58. /// <param name="httpClient">The HTTP client.</param>
  59. /// <param name="url">The URL.</param>
  60. /// <param name="data">The data.</param>
  61. /// <param name="cancellationToken">The cancellation token.</param>
  62. /// <returns></returns>
  63. public static async Task<HttpResponseMessage> GetAsync<T>(this HttpClient httpClient, string url, T data, CancellationToken cancellationToken = default)
  64. {
  65. if (typeof(T).IsArray)
  66. {
  67. var argValues = (data as object[]).Select(v => HttpUtility.UrlEncode(v.ToInvariantString()));
  68. var formContent = string.Join("/", argValues);
  69. return await httpClient.GetAsync(url + "/" + formContent, cancellationToken).ConfigureAwait(false);
  70. }
  71. else
  72. {
  73. var argValues = data.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
  74. .Select(p => $"{p.Name}={HttpUtility.UrlEncode(p.GetValue(data).ToInvariantString())}");
  75. var formContent = string.Join("&", argValues);
  76. return await httpClient.GetAsync(url + "/" + formContent, cancellationToken).ConfigureAwait(false);
  77. }
  78. }
  79. /// <summary>
  80. /// Returns a string that represents the current object, using CultureInfo.InvariantCulture where possible.
  81. /// Dates are represented in IS0 8601.
  82. /// </summary>
  83. public static string ToInvariantString(this object obj)
  84. {
  85. // inspired by: http://stackoverflow.com/a/19570016/62600
  86. return
  87. obj == null ? null :
  88. obj is DateTime dt ? dt.ToString("o", CultureInfo.InvariantCulture) :
  89. obj is DateTimeOffset dto ? dto.ToString("o", CultureInfo.InvariantCulture) :
  90. obj is IConvertible c ? c.ToString(CultureInfo.InvariantCulture) :
  91. obj is IFormattable f ? f.ToString(null, CultureInfo.InvariantCulture) :
  92. obj.ToString();
  93. }
  94. }
  95. }